< 返回我的博客

rdigua 发表于 2021-05-11 01:34

Tags:rust,learning

ref

let maybe_name = Some(String::from("Alice"));
// The variable 'maybe_name' is consumed here ...
match maybe_name {
    Some(n) => println!("Hello, {}", n),
    _ => println!("Hello, world"),
}
// ... and is now unavailable.
println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
let maybe_name = Some(String::from("Alice"));
// Using `ref`, the value is borrowed, not moved ...
match maybe_name {
    Some(ref n) => println!("Hello, {}", n),
    _ => println!("Hello, world"),
}
// ... so it's available here!
println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
let maybe_name = Some(String::from("Alice"));
match maybe_name.as_ref() {
   Some(n) => println!("Hello, {}", n),
    _ => println!("Hello, world"),
}
// still available here

评论区

写评论
作者 rdigua 2021-11-23 11:04

好 加上了

--
👇
cnwzhjs: 也可以这样:

let maybe_name = Some(String::from("Alice"));
match maybe_name.as_ref() {
   Some(n) => println!("Hello, {}", n),
    _ => println!("Hello, world"),
}
// still available here
cnwzhjs 2021-05-11 13:14

也可以这样:

let maybe_name = Some(String::from("Alice"));
match maybe_name.as_ref() {
   Some(n) => println!("Hello, {}", n),
    _ => println!("Hello, world"),
}
// still available here
1 共 2 条评论, 1 页