gpt4 book ai didi

design-patterns - 如何在 Rust 的装饰器模式中使用生命周期说明符?

转载 作者:行者123 更新时间:2023-11-29 08:26:38 30 4
gpt4 key购买 nike

我是使用rust 的新手,还没有得到生命周期说明符的东西。为了将不同的关注点分离到不同的结构中,我尝试做一些类似于装饰器模式的事情。但是,以下代码无法编译:

trait T {
fn foo(self) -> u64;
}

struct Inner {}

impl T for Inner {
fn foo(self) -> u64 {
42
}
}

struct Outer<'a> {
delegate: &'a T,
}

impl<'a> T for Outer<'a> {
fn foo(self) -> u64 {
self.delegate.foo()
}
}

pub fn dec_test() {
let inner = &Inner {};
let outer = Outer{delegate:inner};

println!("Meaning of life: {}", outer.foo());
}

我得到以下错误

error[E0161]: cannot move a value of type dyn T: the size of dyn T cannot be statically determined
--> src/lib.rs:19:9
|
19 | self.delegate.foo()
| ^^^^^^^^^^^^^

error[E0507]: cannot move out of borrowed content
--> src/lib.rs:19:9
|
19 | self.delegate.foo()
| ^^^^^^^^^^^^^ cannot move out of borrowed content

error: aborting due to 2 previous errors

最佳答案

忽略第一个关于unsized types的错误,后两个错误都是关于同一个问题:“cannot move out of borrowed content”

这个较小的示例会触发相同的错误:

struct Inner {}

impl Inner {
// consumes self. requires ownership
fn foo(self) -> u64 {
42
}
}

fn main() {
let my_inner = Inner {};
let borrow = &my_inner;
let answer = borrow.foo(); // oops! we are using a borrowed version that we don't own
println!("meaning of life {}", answer);
}

有关详细信息,请参阅 this answer ,具体关于所有权的部分或参见chapter four of the rust book .

具体针对您的问题,一种解决方法是更改​​ trait T 以便它仅借用其参数:

trait T {
fn foo(&self) -> u64; // notice the change: `self` -> `&self`
}

// ...

impl T for Inner {
fn foo(&self) -> u64 { // notice the change: `self` -> `&self`
42
}
}

// ...

impl<'a> T for Outer<'a> {
fn foo(&self) -> u64 { // notice the change: `self` -> `&self`
self.delegate.foo()
}
}

// ...

关于design-patterns - 如何在 Rust 的装饰器模式中使用生命周期说明符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54778910/

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