Appearance
字符串2: exercises/strings/strings2.rs
题目
rust
// strings2.rs
//
// Make me compile without changing the function signature!
//
// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
let word = String::from("green"); // Try not changing this line :)
if is_a_color_word(word) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");
}
}
fn is_a_color_word(attempt: &str) -> bool {
attempt == "green" || attempt == "blue" || attempt == "red"
}
要求不修改函数签名的情况下,修改代码,让编译通过。
题目解析
看代码里面let word = String::from("green");
声明的是不可变String
函数fn is_a_color_word(attempt: &str) -> bool
的签名里面参数类型为字符串切片&str
两者类型不匹配,我们可以直接借用word
,由于Deref强制转换可以将&String
转换为&str
,这里可以直接使用:
rust
fn main() {
let word = String::from("green"); // Try not changing this line :)
if is_a_color_word(&word) {
if is_a_color_word(&word) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");
}
}
fn is_a_color_word(attempt: &str) -> bool {
attempt == "green" || attempt == "blue" || attempt == "red"
}