gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:40:04 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com