简体   繁体   English

Rust 返回“空”泛型变量

[英]Rust return "empty" generic variable

I want to have a function that let me extract infos from Results.我想要一个让我从结果中提取信息的功能。 The problem is what to return if something fails (the function uses a generic parameter).问题是如果某些事情失败了要返回什么(该函数使用通用参数)。 Here is my code:这是我的代码:

fn check<T, E>(x: Result<T, E>) -> T {
    if let Ok(sk) = x {
        return sk;
    } else {
        println!("uh oh");
        return 0 as T;
    }
}

As you can guess it doesn't work, what should i put instead of 0 as T ?你可以猜到它不起作用,我应该用什么代替0 as T

If you want to return the default value for the type (0 for numbers, false for bools, an empty string for strings etc.) you can constrain it to T: Default and return T::default() :如果要返回类型的默认值(数字为 0,布尔为false ,字符串为空字符串等),您可以将其约束为T: Default并返回T::default()

fn check<T: Default, E>(x: Result<T, E>) -> T {
    if let Ok(sk) = x {
        return sk;
    } else {
        println!("uh oh");
        return T::default();
    }
}

But note that there is an existing method on Result that returns the default value in case of Err : unwrap_or_default() .但请注意,在Result上有一个现有方法在Err的情况下返回默认值: unwrap_or_default()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM