[Rust] .into()

pub fn generate_nametag_text(name: String) -> Result<String, String> {
    if name.is_empty() {
        // Empty names aren't allowed.
        Err(String::from("`name` was empty; it must be nonempty."))
    } else {
        Ok(format!("Hi! My name is {}", name))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generates_nametag_text_for_a_nonempty_name() {
        assert_eq!(
            generate_nametag_text("Beyoncé".into()),
            Ok("Hi! My name is Beyoncé".into())
        );
    }

    #[test]
    fn explains_why_generating_nametag_text_fails() {
        assert_eq!(
            generate_nametag_text("".into()),
            // Don't change this line
            Err("`name` was empty; it must be nonempty.".into())
        );
    }
}

The .into()method in rust is used to convert one type into another. Here .into() is used to convert a string literal (which has the type &str) into a String type.

This is necessary due to when you call generate_nametag_text("Beyoncé".into()), "Beyoncé" is a string literal of type &str. Using .into() here converts it into a String.

In Rust, string literals are of type &str, which are borrowed references to a string. The String type, on the other hand, is an owned, growable string. The generate_nametag_text function expects an argument of type String, not &str.

posted @ 2024-03-01 15:49  Zhentiw  阅读(30)  评论(0)    收藏  举报