“借入的价值不能活得足够长"具有返回impl trait的泛型函数 [英] "borrowed value does not live long enough" with a generic function that returns impl trait
问题描述
我从此Rust代码收到意外错误:
I get an unexpected error from this Rust code:
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)
}
错误是:
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 = 123;
14 | let a = Container { x: &i };
| ^^ borrowed value does not live long enough
15 | json(&a)
16 | }
| - `i` dropped here while still borrowed
为什么?
如果将 json()
的声明更改为以下两个版本之一,则代码将编译:
If I change the declaration of json()
to either of these versions, the code compiles:
fn json(val: &Container) -> impl Reply
fn json<T>(val: &T) -> i32
只有在同时具有类型参数和返回的特征对象的情况下,编译器才会拒绝代码.
It is only when there is both a type parameter and a returned trait object that the compiler rejects the code.
这是我们对 warp :: reply :: json()
遇到的一个实际问题的减少,但是我更希望从总体上理解它.
This is a reduction from a real issue we had with warp::reply::json()
, but I would prefer to understand it in general.
推荐答案
当参数和函数的返回类型是通用的时,Rust编译器假定返回类型可能会借用参数.这就是为什么它假定 f()
返回一个引用局部变量 i
的值.
When the arguments and the return type of a function are generic, the Rust compiler assumes that the return type could, potentially, borrow the arguments. That's why it assumes that f()
returns a value referencing the local variable i
.
我不确定,但是我认为这是理想的,因为有人可以针对可能会出现问题的类型实现 Reply
.
I'm not entirely sure, but I think this is desired, because someone could implement Reply
for a type where this would be problematic.
由于存在错误,因此无法使用.已经在GitHub上进行了报道.
This doesn't work because of a bug. It has already been reported on GitHub.
这篇关于“借入的价值不能活得足够长"具有返回impl trait的泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!