Strings
Stringcan be mutated.&strborrowed, immutable string slice.References:
strings1.rs
// TODO: Fix the compiler error without changing the function signature.
fn current_favorite_color() -> String {
String::from("blue")
}
fn main() {
let answer = current_favorite_color();
println!("My current favorite color is {answer}");
}In this exercise the function is expecting
Stringas return type but got&strinstead."hello"is&strand we just need to convert it intoString.We can use either one of below expressions:
String::from("blue") "blue".to_string()
strings2.rs
Similar problem with previous exercise.
The function is expecting
&strbut gotStringinstead.So we can convert it using either codes below:
strings3.rs
In this exercise we have 3 task.
First is to trim given
&strin functiontrim_meand return&str.We can use
trimmethod to do this.
Second is to add
" world!"into given&strin functioncompose_me.We have multiple option to do this.
But because
&stris immutable we cannot just simply use+.We can either convert it into
Stringfirst or useformatmacro like below.
Last is to replace occurrence of
carstoballoonsin functionreplace_me.We can do this by using
replacemethod.
strings4.rs
In this exercise we need to replace
placeholderwith eitherstringorstring_slicefor given parameters.I explain each of the line below:
Basically anything that require string manipulation usually return
Stringand if no string manipulation usually return&str
Last updated