gpt4 book ai didi

rust - 可变引用在直接调用函数时生命周期足够长,但在通过中间函数调用时生命周期不够长

转载 作者:行者123 更新时间:2023-11-29 08:05:12 25 4
gpt4 key购买 nike

对于以下 Rust 代码:

fn facing_of_mut<'a>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut Direction> {
component_of_mut(&mut domain, entity)
}

...编译器输出:

error: `domain` does not live long enough
--> src/facing.rs:5:27
|
5 | component_of_mut(&mut domain, entity)
| ^^^^^^ does not live long enough
6 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 4:90...
--> src/facing.rs:4:91
|
4 | fn facing_of_mut<'a>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut Direction> {
| ___________________________________________________________________________________________^ starting here...
5 | | component_of_mut(&mut domain, entity)
6 | | }
| |_^ ...ending here

我不明白错误消息,因为我认为声明这些生命周期的目的是明确要求作为 domain 参数传递的任何对象只要 Direction 返回值中的引用取决于 domain 分配的内存。

component_of_mut 的签名是:

pub fn component_of_mut<'a, C: 'static>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut C>

...而且我可以在单元测试中直接调用它,而不会在编译期间出现生命周期错误。只有当 facing_of_mut 调用它时,我才会遇到错误。

最佳答案

您正在引用domain 是参数的局部变量并且已经是一个引用。 domain 仅在函数调用期间持续,因此该值的引用可以存在多长时间。

要修复它,请不要尝试引用引用:

type Domain = String;
type Entity = String;
type Direction = String;

pub fn component_of_mut<'a, C>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut C>
where C: 'static
{
unimplemented!()
}

fn facing_of_mut<'a>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut Direction> {
component_of_mut(domain, entity)
}

fn main() {}

关于rust - 可变引用在直接调用函数时生命周期足够长,但在通过中间函数调用时生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42195849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com