< 返回我的博客

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()));

评论区

写评论
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 共 1 条评论, 1 页