fn lifetime_tester<A, B, C>(a: Box<A>, b: Box<B>, c: &i32) -> &i32 {
c
}
fn main() {
let a = Box::new(String::from("Test1"));
let b = Box::new(55 as i32);
let c: i32;
{
c = 34 as i32;
}
println!("{}", lifetime_tester(a, b, &c));
}
Error:
error[E0282]: type annotations needed
--> src/main.rs:12:20
|
12 | println!("{}", lifetime_tester(a, b, &c));
| ^^^^^^^^^^^^^^^ cannot infer type for `C`
我对“类型注释”需要去哪里感到困惑。我已将返回类型指定为&i32
,我指定了一个参数类型&i32
我还指定了c
is an i32
.
由于函数的参数和泛型类型之间没有链接C
,编译器不知道您要替换哪种类型C
在函数调用中。在这种情况下,您的代码甚至不使用类型C
所以这并不重要,但 Rust 很注重“本地推理”——也就是说,它不会窥视你的函数内部来确定你没有使用C
在语法检查阶段。
您可以使用“turbofish”运算符明确告诉它您的类型是什么,::<>
, 像这样
println!("{}", lifetime_tester::<_, _, i32>(a, b, &c));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)