这是什么展开的东西:有时是展开有时是 unwrap_or [英] What is this unwrap thing: sometimes it's unwrap sometimes it's unwrap_or
问题描述
注意 这个问题中关于 read_line
和 ~str
的细节与 Rust 1.0 之前的版本有关.unwrap
和 unwrap_or
的一般概念仍然适用.
Note The specifics in this question regarding
read_line
and~str
pertain to a pre-1.0 version of Rust. The general concepts aboutunwrap
andunwrap_or
remain relevant.
我在阅读 Rust for Rubyists 时遇到了它,即:>
let mut reader = BufferedReader::new(io::stdin());
let input = reader.read_line().unwrap_or(~"nothing");
推荐答案
注意 这个答案中关于
read_line
和~str
的细节与 Rust 1.0 之前的版本有关.unwrap
和unwrap_or
的一般概念仍然适用.
Note The specifics in this answer regarding
read_line
and~str
pertain to a pre-1.0 version of Rust. The general concepts aboutunwrap
andunwrap_or
remain relevant.
因为 read_line
可能会失败,所以它返回 Option<~str>
.要获取值,您可以使用模式匹配或解包方法之一.
Because read_line
might fail it returns Option<~str>
. To get the value out you can use pattern matching or one of the unwrap methods.
unwrap
和 unwrap_or
的区别在于,如果没有值(None
),unwrap
会失败但 unwrap_or
将返回指定的默认值(在本例中为nothing")
The difference between unwrap
and unwrap_or
is that unwrap
will fail if there is no value (None
) but unwrap_or
will return the specified default ("nothing" in this case)
这篇关于这是什么展开的东西:有时是展开有时是 unwrap_or的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!