Appearance
字符串1: exercises/strings/strings1.rs
题目
rust
// strings1.rs
//
// Make me compile without changing the function signature!
//
// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
let answer = current_favorite_color();
println!("My current favorite color is {}", answer);
}
fn current_favorite_color() -> String {
"blue"
}
要求不修改函数签名的情况下,修改代码,让编译通过。
题目解析
这道题其实就是String的定义,"blue"
的类型是&str
,与函数签名返回值String
不匹配。
rust
fn current_favorite_color() -> String {
"blue"
"blue".into()
}
rust
fn current_favorite_color() -> String {
"blue"
"blue".to_string()
}
或者使用String::from
:
rust
fn current_favorite_color() -> String {
"blue"
String::from("blue")
}