rust - 这个展开的东西是什么 : sometimes it's unwrap sometimes it's unwrap_or

标签 rust

Note The specifics in this question regarding read_line and ~str pertain to a pre-1.0 version of Rust. The general concepts about unwrap and unwrap_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 about unwrap and unwrap_or remain relevant.

Rust 有解释这些事情的 API 文档。

BufferedReader.read_line :

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 return None—if the condition is handled. If it's not it'll fail and so you'll never get anything back.]

您还将获得 None如果在阅读器中阅读了所有内容,则返回。


Option.unwrap :

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()失败

Option.unwrap_or :

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/

相关文章:

rust - 有没有办法在 Rust 中创建指向方法的函数指针?

rust - 将闭包传递给特征方法 : expected type parameter, 找到闭包

reference - 在 rust 中保持干燥

rust - 如何使用 toml-rs 检查 TOML 中是否存在 key ?

rust - 为什么需要在循环的每次迭代中声明一个变量才能使用它?

arrays - Rust中的耦合数组

generics - 集合中的扩展特征

localization - 如何在 Rust 中更改格式化程序的小数点分隔符?

rust - 如何实现自定义 'fmt::Debug' 特征?

Rustc/LLVM 使用 opt-level=0 为 aarch64 生成错误代码