Rust代码示例——18.4.2.Result的别名

当我们想要多次使用特定的Result类型该怎么办呢?回忆一下Rust的内容,它可以让我们建立别名。因此我们可以为特定Result定义一个别名。

在模块级别,建立别名是特别有帮助的。在特定模块中出现的错误通常有相同的错误类型,因此一个别名可以简洁的定义所有的相关Result。它是如此有用,以致于标准库都提供了一个:io::Result。

下面示例展示了这种语法:

use std::num::ParseIntError;


// Define a generic alias for a `Result` with the error type `ParseIntError`.

type AliasedResult<T> = Result<T, ParseIntError>;


// Use the above alias to refer to our specific `Result` type.

fn multiply(first_number_str: &str, second_number_str: &str) -> AliasedResult<i32> {

    first_number_str.parse::<i32>().and_then(|first_number| {

        second_number_str.parse::<i32>().map(|second_number| first_number * second_number)

    })

}


// Here, the alias again allows us to save some space.

fn print(result: AliasedResult<i32>) {

    match result {

        Ok(n)  => println!("n is {}", n),

        Err(e) => println!("Error: {}", e),

    }

}


fn main() {

    print(multiply("10", "2"));

    print(multiply("t", "2"));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值