我从此Rust代码收到意外错误:
struct Container<'a> {
x: &'a i32,
}
trait Reply {}
impl Reply for i32 {}
fn json<T>(_val: &T) -> impl Reply {
3
}
fn f() -> impl Reply {
let i = 123;
let a = Container { x: &i };
json(&a)
}
Run Code Online (Sandbox Code Playgroud)
错误是:
error[E0597]: `i` does not live long enough
--> src/lib.rs:14:28
|
12 | fn f() -> impl Reply {
| ---------- opaque type requires that `i` is borrowed for `'static`
13 | let i …Run Code Online (Sandbox Code Playgroud) 我有一个关联类型的特征:
pub trait Speak {
type Error;
fn speak(&self) -> Result<String, Self::Error>;
}
Run Code Online (Sandbox Code Playgroud)
该特征的实现:
#[derive(Default)]
pub struct Dog;
impl Speak for Dog {
type Error = ();
fn speak(&self) -> Result<String, Self::Error> {
Ok("woof".to_string())
}
}
Run Code Online (Sandbox Code Playgroud)
并且函数返回该实现的实例:
pub fn speaker() -> impl Speak {
Dog::default()
}
Run Code Online (Sandbox Code Playgroud)
我知道在这个例子中我只能Dog用作返回类型,但在我的实际代码中我必须使用impl Speak(上面的函数实际上是由宏生成的).
据我了解,该impl Trait符号让出这实际上返回具体类型编译器的身影,所以我希望下面的函数正确编译,因为speaker()回报Dog,并且Dog::Error是类型():
fn test() -> Result<String, ()> {
speaker().speak()
}
Run Code Online (Sandbox Code Playgroud)
相反,我收到以下错误:
error[E0308]: mismatched types
--> src/lib.rs:21:5
| …Run Code Online (Sandbox Code Playgroud)