gpt4 book ai didi

rust - 将方法从特征实现移动到特征定义时出现类型不匹配错误

转载 作者:行者123 更新时间:2023-11-29 08:07:57 24 4
gpt4 key购买 nike

我有两个结构,VMWord。我需要一个新结构 Control,它的行为就像 VM,但多了一个字段 master。因为 Rust 没有继承,所以我尝试通过组合来扩展结构。我将VM的功能移动到一个新的traitCore中,并为Control实现了Core。生成的代码有效。

struct Word<T> {
action: fn(target: &T)
}

struct VM {
word: Word<VM>
}

trait Core<T> {
fn word(&self) -> &Word<T>;
fn hello(&self) { println!("Hello"); }
fn execute(&self);
}

impl Core<VM> for VM {
fn word(&self) -> &Word<VM> { &self.word }
fn execute(&self) { (self.word().action)(self); }
}

struct Control {
word: Word<Control>,
master: i32,
}

impl Core<Control> for Control {
fn word(&self) -> &Word<Control> { &self.word }
fn execute(&self) { (self.word().action)(self); }
}

fn main() {
let vm = VM{
word: Word {action: Core::hello}
};
vm.execute();
let control = Control{
word: Word {action: Core::hello},
master: 0,
};
vm.execute();
}

execute 的两个实现是相同的。所以我将 execute 移动到 trait Core 中。

trait Core<T> {
fn word(&self) -> &Word<T>;
fn hello(&self) { println!("Hello"); }
fn execute(&self) { (self.word().action)(self); }
}

impl Core<VM> for VM {
fn word(&self) -> &Word<VM> { &self.word }
}

impl Core<Control> for Control {
fn word(&self) -> &Word<Control> { &self.word }
}

编译时出现以下错误:

main.rs:14:44: 14:48 error: mismatched types:
expected `&T`,
found `&Self`
(expected type parameter,
found Self) [E0308]
main.rs:14 fn execute(&self) { (self.word().action)(self); }

我该如何解决这个问题?

最佳答案

如果你移动执行在Core ,特征定义中没有任何内容表明 TSelf 的类型相同.

trait Core<T> {
fn word(&self) -> &Word<T>;
fn hello(&self) { println!("Hello"); }
fn execute(&self) {
(self.word() // this is a &Word<T>
.action) // this is a fn(T)
(self); // this type is Self. T is not necessarily = Self
}
}

executeimpl Core<Control> for Control , impl 表示 SelfT都是 = Control , 所以 execute作品。但是如果 T 可以是特征定义中的任何东西,Rust 就不能让你的代码编译。

如何修复它取决于您需要做什么。

如果你的特征总是要以这种方式实现(impl Core<Something> for Somethingimpl Core<SomethingElse> for SomethingElse 但绝不是 impl Core<Something> for SomethingElse ),你可以从特征定义中删除参数并只:

trait Core: Sized {
fn word(&self) -> &Word<Self>; // now you can't parametrize what
// Word to return. It will be Self.
fn hello(&self) { println!("Hello"); }
fn execute(&self) { (self.word().action)(self); } // ...and this works
}

关于rust - 将方法从特征实现移动到特征定义时出现类型不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507941/

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