gpt4 book ai didi

rust - 尝试使用 Box<_> 应用多态性时出现错误 "cannot move a value ... the size cannot be statically determined"

转载 作者:行者123 更新时间:2023-11-29 08:34:22 37 4
gpt4 key购买 nike

我正在应用多态性 solution在 Rust 中解决我的问题。我想将此解决方案与 Box<_> 一起使用因为它看起来最直接和简单,但它不起作用。

#[derive(Clone, Copy)]
pub struct NewPost;

#[derive(Clone, Copy)]
pub struct Post;

#[derive(Clone, Copy)]
pub struct PgConnection;

#[derive(Clone, Copy)]
pub struct DBPost;

pub trait DBAdapter {
fn create(self, post: NewPost) -> Post;
fn read(self) -> Vec<Post>;
}

impl DBPost {
// DATABASE classes
pub fn establish_connection(self) -> PgConnection {
unimplemented!()
}
}

impl DBAdapter for DBPost {
fn create(self, _post: NewPost) -> Post {
unimplemented!()
}

fn read(self) -> Vec<Post> {
unimplemented!()
}
}

struct GetPostsCase {
db: Box<dyn DBAdapter>,
}

impl GetPostsCase {
pub fn new(db: Box<dyn DBAdapter>) -> GetPostsCase {
GetPostsCase { db: db }
}

pub fn run(&self) -> Vec<Post> {
let result = self.db.read();
result
}
}

错误是:

error[E0161]: cannot move a value of type dyn DBAdapter: the size of dyn DBAdapter cannot be statically determined
--> src/lib.rs:45:22
|
45 | let result = self.db.read();
| ^^^^^^^

error[E0507]: cannot move out of `*self.db` which is behind a shared reference
--> src/lib.rs:45:22
|
45 | let result = self.db.read();
| ^^^^^^^ move occurs because `*self.db` has type `dyn DBAdapter`, which does not implement the `Copy` trait

最佳答案

您的 read 方法采用(未调整大小的)值而不是采用引用(其大小始终相同)。

可以通过更改DBAdapter的契约来解决问题

来自

fn read(self) -> Vec<Post> {

fn read(&self) -> Vec<Post> {
// ^--- added the ampersand

(根据您的实现,您可能需要 &mut)

关于rust - 尝试使用 Box<_> 应用多态性时出现错误 "cannot move a value ... the size cannot be statically determined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57660881/

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