rust - 错误: unable to infer enough type information about `_` ; type annotations required

标签 rust

尝试编译此代码时出现一个奇怪的错误:

pub trait ValueGiver<T> {
    fn give(_: Option<Self>) -> T;
}

struct m;

impl<f64> ValueGiver<f64> for m {
    fn give(_:Option<m>) -> f64 {
        0.5f64
    } 
}

fn main() {
    let y : f64 = ValueGiver::give(None::<m>);
}

playpen

(选项部分是调用静态特征方法的技巧)

我明白了:

c.rs:64:5: 68:6 error: unable to infer enough type information about `_`; type annotations required
c.rs:64     impl<f64> ValueGiver<f64> for m {
c.rs:65         fn give(_:Option<m>) -> f64 {
c.rs:66             0.5f64
c.rs:67         } 
c.rs:68     }

不知道哪部分不清楚,无法推断,错误信息也没有多大帮助

最佳答案

替换 impl<f64>只需 impl . 您不需要通用的 impl,您需要特定的 impl。你会写 impl<T> 定义类型参数,您可以稍后在实现中使用;你在这里不需要这个。

当你写impl<f64>时,这个f64被解释为类型参数。但是,所有其他出现 f64 的情况在 impl 中被解释为 f64关键字,指定原语 f64类型。编译器提示是因为它无法推断 f64 的具体类型。输入参数。

如果我们替换impl<f64>impl<T> , we get the same error .

关于rust - 错误: unable to infer enough type information about `_` ; type annotations required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27218117/

相关文章:

string - 如果字符串文字在整个程序期间都处于事件状态,那么它们如何具有不同的生命周期?

rust - 从 Rust 库返回指向对象的指针供以后重用?

rust - 如何为openssl::ssl::SslStream创建BufReader?

rust - 为什么我们不需要从某些 Rust 迭代器中的 Result 中提取值?

rust - 核心中的运算符真的是循环定义的吗?

parallel-processing - 如何使用 Rayon 检测整数总和的溢出?

rust - Rust Rocket 如何推断包含在结果/选项中的返回类型?

rust - 为什么在使用非文字模式时无法访问此匹配模式?

rust - 如何将 tokio::timer::Timeout 与 Future::wait 一起使用?

rust - 为什么这会在打印前读取输入?