实现说明
真正干活的是函数 register_user、normalized_len、main,其余都是接线。
使用要点
- 每一步打印都带着自己的标签:
len static:、len owned:、still usable:。 main按顺序串起register_user、normalized_len;运行文件就会把这个流程跑一遍。
常见问题
运行「Into 与 AsRef 接受任意字符串形态」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 len static:、len owned:、still usable: 标签标明各步骤。
签名一览:fn register_user(name: impl Into<String>) -> String
核心语句
fn register_user(name: impl Into<String>) -> String {
// Into 消费参数:String 传入零开销,&str 传入才分配
let owned: String = name.into();
format!("registered: {owned}")
}
fn normalized_len(text: impl AsRef<str>) -> usize {
// AsRef 只借用:任何能借成 &str 的值都能传入
text.as_ref().trim().len()
}
代码示例
// Into<String>:调用方决定是否转移所有权;AsRef<str>:只读借用,零拷贝
fn register_user(name: impl Into<String>) -> String {
// Into 消费参数:String 传入零开销,&str 传入才分配
let owned: String = name.into();
format!("registered: {owned}")
}
fn normalized_len(text: impl AsRef<str>) -> usize {
// AsRef 只借用:任何能借成 &str 的值都能传入
text.as_ref().trim().len()
}
fn main() {
// &str 传入 Into:需要时才分配出 String
println!("{}", register_user("alice"));
let heap_name = String::from("bob");
// String 传入 Into:所有权直接转移,没有第二次分配
println!("{}", register_user(heap_name));
// AsRef<str> 同时接受 &str 与 &String
println!("len static: {}", normalized_len(" carol "));
let owned = String::from(" dave ");
println!("len owned: {}", normalized_len(&owned));
// 被借用的值不受影响,之后仍可继续使用
println!("still usable: {}", owned.to_uppercase());
}