Strings

  • String can be mutated.

  • &str borrowed, 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 String as return type but got &str instead.

  • "hello" is &str and we just need to convert it into String.

  • 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 &str but got String instead.

  • So we can convert it using either codes below:

strings3.rs

  • In this exercise we have 3 task.

  • First is to trim given &str in function trim_me and return &str.

    • We can use trim method to do this.

  • Second is to add " world!" into given &str in function compose_me.

    • We have multiple option to do this.

    • But because &str is immutable we cannot just simply use +.

    • We can either convert it into String first or use format macro like below.

  • Last is to replace occurrence of cars to balloons in function replace_me.

    • We can do this by using replace method.

strings4.rs

  • In this exercise we need to replace placeholder with either string or string_slice for given parameters.

  • I explain each of the line below:

  • Basically anything that require string manipulation usually return String and if no string manipulation usually return &str

Last updated