官术网_书友最值得收藏!

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 153字
  • 2021-07-02 23:07:23

The use of expect

Rust contains a very useful function called expect. This method is used with any form of call that has an Option or a Result type (for example, Result in the file-writing example has the options of File or Error). It works by moving the value out of the option and returning it. If the option/result type contains an error, the expect call stops your program and prints out the error message.

For example, the following statement will return either File or Error into file:

let file: Result<File, Error> = options.open("my_file.txt").expect("Opening the file failed"); 

A shorter form is available in the unwrap method. This is the same as the expect method, but it doesn't print out anything in case of a failure. In general, Some(a).unwrap() will return a.

Expect is usually favored instead of unwrap, since the full error message makes it easier to find where the error came from.

主站蜘蛛池模板: 通化市| 长岛县| 日喀则市| 巴林右旗| 铁岭市| 芮城县| 扎赉特旗| 拉萨市| 谷城县| 泰顺县| 宣武区| 惠东县| 日喀则市| 南阳市| 山阴县| 马边| 兴仁县| 含山县| 阿瓦提县| 枣庄市| 南华县| 唐河县| 桓仁| 安吉县| 南乐县| 大荔县| 广灵县| 云安县| 谢通门县| 英吉沙县| 青龙| 疏勒县| 兴安盟| 宿州市| 翁牛特旗| 集安市| 福海县| 千阳县| 会理县| 临沧市| 宁明县|