如何从 中返回默认值Option<&String>?
这是我的示例/最小代码:
fn main() {
let map = std::collections::HashMap::<String, String>::new();
let result = map.get("").or_else(|| Some("")).unwrap(); // <== I tried lots of combinations
println!("{}", result);
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以做这样的事情......
let value = match result {
Some(v) => v,
None => "",
};
Run Code Online (Sandbox Code Playgroud)
...但我想知道是否可以用or_elseor来实现它unwrap_or_else?(使默认值变得惰性很重要,因此如果不使用它就不会被计算)
这些是我尝试过的一些编译器建议(我可以将它们全部放入,因为 SO 不允许我这样做):
7 | let result = map.get("").or_else(|| Some("") ).unwrap();
| ^^ expected struct `String`, found `str`
Run Code Online (Sandbox Code Playgroud)
。
7 | let result = map.get("").or_else(|| Some(&"".to_string()) ).unwrap();
| ^^^^^^--------------^
| | |
| | temporary value created here
| returns a value referencing data owned by the current function
Run Code Online (Sandbox Code Playgroud)
。
7 | let result = map.get("").or_else(|| Some(String::new()) ).unwrap();
| ^^^^^^^^^^^^^
| |
| expected `&String`, found struct `String`
|
help: consider borrowing here: `&String::new()`
Run Code Online (Sandbox Code Playgroud)
。
7 | let result = map.get("").or_else(|| Some(&String::new()) ).unwrap();
| ^^^^^^-------------^
| | |
| | temporary value created here
| returns a value referencing data owned by the current function
Run Code Online (Sandbox Code Playgroud)
。并且
6 | let result = map.get("").unwrap_or_else(|| ""); // I tried lots
| ^^ expected struct `String`, found `str`
|
= note: expected reference `&String`
found reference `&'static str`
Run Code Online (Sandbox Code Playgroud)
如果您确实需要 a&String作为result,您可以创建一个String具有足够长生命周期的默认值。
fn main() {
let map = std::collections::HashMap::<String, String>::new();
let default_value = "default_value".to_string();
let result = map.get("").unwrap_or(&default_value);
println!("{}", result);
}
Run Code Online (Sandbox Code Playgroud)
default_value如果默认值是编译时固定值,则可以通过使用来避免分配&str。
fn main() {
let map = std::collections::HashMap::<String, String>::new();
let result = map.get("")
.map(String::as_str)
.unwrap_or("default_value");
println!("{}", result);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9023 次 |
| 最近记录: |