这是什么展开的东西:有时是展开有时是 unwrap_or [英] What is this unwrap thing: sometimes it's unwrap sometimes it's unwrap_or

查看:57
本文介绍了这是什么展开的东西:有时是展开有时是 unwrap_or的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意 这个问题中关于 read_line~str 的细节与 Rust 1.0 之前的版本有关.unwrapunwrap_or 的一般概念仍然适用.

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");

推荐答案

注意 这个答案中关于 read_line~str 的细节与 Rust 1.0 之前的版本有关.unwrapunwrap_or 的一般概念仍然适用.

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.

因为 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.

unwrapunwrap_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆