gpt4 book ai didi

rust - 如何不借钱就能确保 self 超越返回值(value)

转载 作者:行者123 更新时间:2023-12-03 11:39:31 25 4
gpt4 key购买 nike

假设有这样的事情:

trait B {}
struct BB {}
impl B for BB {}

struct A {}
impl A {
// With this, A can be dropped before B
// fn get_b(&mut self) -> Box<dyn B> {...}

fn get_b<'a>(&'a mut self) -> Box<dyn B + 'a> {...}
fn mut_a(&mut self) {}
}

fn main() {
let mut a = A {};
let b = a.get_b();

// These lines don't compile
a.mut_a(); // A is borrowed. Is there any way to make this compile?

// Does not compile and should not. b must be dropped before a
drop(a);
drop(b);
}


有什么方法可以确保 a超过 b(出于 unsafe代码的原因)而又不让 a借用?

编辑: ab都必须是可变的(如果声明了 mut)并且应该保持可移动状态。它唯一需要确保的是B在A之前被丢弃。

最佳答案

如果给A两个字段,例如lifetimedata,则可以让get_b接受对lifetime的共享引用,让mut_a接受对data的可变引用:

trait B {}
struct BB {}
impl B for BB {}

struct A {
pub lifetime: ALifetime,
pub data: AData,
#[allow(dead_code)]
private: (), // prevent destructuring
}
struct ALifetime {}
struct AData {}
impl A {
fn new() -> Self {
Self { lifetime: ALifetime {}, data: AData {}, private: () }
}
}
impl ALifetime {
fn get_b<'a>(&'a self) -> Box<dyn B + 'a> { Box::new(BB{}) }
}
impl AData {
fn mut_a(&mut self) {}
}

fn main() {
let mut a = A::new();
let b = a.lifetime.get_b();
a.data.mut_a(); // Only `a.data` is borrowed here.
// drop(b);
drop(a); // Not allowed. b must be dropped before a
}

游乐场: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ccd1a25cacd21d4364f2f3add1499015

关于rust - 如何不借钱就能确保 self 超越返回值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62113457/

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