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");
最佳答案
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.
Rust 有解释这些事情的 API 文档。
fn read_line(&mut self) -> Option<~str>
Reads the next line of input, interpreted as a sequence of UTF-8 encoded unicode codepoints. If a newline is encountered, then the newline is contained in the returned string.
…
[Then something about raising the
io_error
condition, which is one situation in which it would returnNone
—if the condition is handled. If it's not it'll fail and so you'll never get anything back.]
您还将获得 None
如果在阅读器中阅读了所有内容,则返回。
fn unwrap(self) -> T
Moves a value out of an option type and returns it.
Useful primarily for getting strings, vectors and unique pointers out of option types without copying them.
…
也就是说,
-
Some(a).unwrap()
返回a
-
None.unwrap()
失败
fn unwrap_or(self, def: T) -> T
Returns the contained value or a default
也就是说,
-
Some(a).unwrap_or(b)
返回a
-
None.unwrap_or(b)
返回b
关于rust - 这个展开的东西是什么 : sometimes it's unwrap sometimes it's unwrap_or,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21257686/