Rustlings Topic: Strings

Rust has two string types, a string slice (&str) and an owned string (String). We’re not going to dictate when you should use which one, but we’ll show you how to identify and create them, as well as use them.

You may find solution code for the topic from my repo.

  1. strings1.rs
  2. strings2.rs

strings1.rs

The current_favorite_color() function is currently returning a string slice with the 'static lifetime. But function signature suggests that it should return String type instead.

Any structure that implements Trait ToString may converted to the String type by calling to_string() method. Or with from() method implemented by Trait From. We haven’t covered the topic about trait in rustlings yet, but this is one of the core feature of Rust. So it is worth reading the Traits chapter from the Book.

/* file: "exercises/strings/strings1.rs" */
fn main() {
    let answer = current_favorite_color();
    println!("My current favorite color is {}", answer);
}

fn current_favorite_color() -> String {
    // "blue".to_string()
    String::from("blue")
}

strings2.rs

What is the problem with the code? Let’s check what compiler says about it.

error[E0308]: mismatched types
 --> exercises/strings/strings2.rs:7:24
  |
7 |     if is_a_color_word(word) {
  |                        ^^^^
  |                        |
  |                        expected `&str`, found struct `String`
  |                        help: consider borrowing here: `&word`

Why does compiler expects string slice(&str)? Because function signature says so.

fn is_a_color_word(attempt: &str) -> bool

Rustlings comment says we shouldn’t modify function signature. So we have to modify argument to pass &str instead of String as compiler suggests.

Rust compiler knows a lot, and it’s suggestion is worth reading. So anytime compiler refuses to compile your code, it is wise to check the error message.

/* file: "exercises/strings/strings2.rs" */
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"
}

Continue with Rustlings Solution