[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 @   Zhentiw  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-03-01 [Typescript] Clean type
2020-03-01 [Debug] debug module
2020-03-01 [CLI] Create a Hybrid Single-Multi Command Node.js CLI with Oclif and TypeScript
2020-03-01 [CLI] Convert a Single Command CLI into a Multi Command CLI with Oclif and TypeScript
2020-03-01 [CLI] Create a Single-Command Node.js CLI with Oclif, TypeScript and Yarn Workspaces
2020-03-01 [Custom CLI] Develop and Publish a Node.js CLI from Scratch
2019-03-01 [Compose] 21. Apply Natural Transformations in everyday work
点击右上角即可分享
微信分享提示