代码:
fn hello(name: &String) {
println!("Name is {}", name);
}
fn greet(name: &str) {
println!("Name is {}", name);
}
fn main() {
let option_name: Option<String> = Some("Alice".to_owned());
// let r: Option<&String> = option_name.as_ref();
option_name.as_ref().map(hello);
// let r2: Option<&str> = option_name.as_deref();
option_name.as_deref().map(greet);
println!("{:?}", option_name);
// as_deref 将 Option<String> 转换成 &str,配合 unwrap_or 的返回值也是 &str,统一了返回值类型
let r3 = option_name.as_deref().unwrap_or("undefined");
println!("{:?}", r3);
}
标签:option,name,let,deref,ref,rust,Option
From: https://www.cnblogs.com/lemos/p/16876115.html