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

  • 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.

主站蜘蛛池模板: 宁武县| 塔河县| 体育| 南开区| 瑞昌市| 无极县| 从江县| 新郑市| 乌兰察布市| 虹口区| 芒康县| 平阳县| 三江| 固原市| 南昌市| 阳新县| 霍山县| 伊金霍洛旗| 仪陇县| 拉萨市| 哈巴河县| 武义县| 公主岭市| 安达市| 保定市| 工布江达县| 新蔡县| 岱山县| 江达县| 兴义市| 明水县| 专栏| 天镇县| 商水县| 嘉峪关市| 彭阳县| 柞水县| 游戏| 吕梁市| 涞源县| 青铜峡市|