[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
.
分类:
Rust
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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