gpt4 book ai didi

rust - 如何在rust中返回带有引用的结构?

转载 作者:行者123 更新时间:2023-12-03 11:44:33 30 4
gpt4 key购买 nike

关闭。这个问题需要details or clarity .它目前不接受答案。












想改进这个问题?通过 editing this post 添加详细信息并澄清问题.

1年前关闭。




Improve this question




我正在使用 crossbeam-epoch在 rust 中编写无锁数据结构。 crossbeam-epoch使用 guard加载堆分配的原子指针。数据结构接口(interface)的一个示例是:

fn get(&self, index: IndexType, guard: &'guard Guard) -> Option<&'guard Value>
此方法需要 guard它与返回值的引用具有相同的生命周期。
现在,我想包装这个方法而不提供 Guard .例如:
struct ReturnType<'guard, Value> {
guard: Guard,
value: Option<&'guard Value>
}

impl<'guard, Value> MyDataStructure<Value> {
fn my_get(&self, index: IndexType) -> ReturnType<'guard, Value> {
let guard = pin();
let value = self.get(index, &guard);
ReturnType {
guard: guard,
value: value
}
}
}
但是编译器不允许我这样做。
我的问题是如何实现方法 my_get ?

最佳答案

这个问题需要改进。您应该始终添加 minimal reproducable example而且您也没有显示编译器错误是什么。
无论如何,在您的代码中,您只是忘记指定生命周期应该链接到什么。如果守卫至少活到 self ,那么你应该声明你的方法:

fn my_get<'guard>(&'guard self, index: IndexType) -> ReturnType<'guard, Value> {
&'guard self告诉编译器链接 'guardself .
如果守卫的生命周期应该比结构长,那么你必须移动 Value或者如果您想分享引用,请使用 Arc<Value> ( Documentation)

关于rust - 如何在rust中返回带有引用的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64609019/

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