gpt4 book ai didi

rust - 特征和关联类型

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

我正在尝试在 Rust 上实现一些具有特征和关联类型的东西。我不确定如何用文字来表达我的问题,所以我将添加一个代码片段,希望它能说明我正在尝试做的事情。

pub trait Person {}

pub trait Directory<P: Person> {
type Per = P;
fn get_person(&self) -> Self::Per;
}

pub trait Catalog {
type Per : Person;
type Dir : Directory<Self::Per>;

fn get_directory(&self) -> Self::Dir;
}

fn do_something<C>(catalog: C) where C: Catalog {
let directory : C::Dir = catalog.get_directory();

// let person : C::Per = directory.get_person();
// The code above fails with:
// error: mismatched types:
// expected `<C as Catalog>::Per`,
// found `<<C as Catalog>::Dir as Directory<<C as Catalog>::Per>>::Per`
// (expected trait `Catalog`,
// found trait `Directory`) [E0308]

let person = directory.get_person();
do_something_with_person(person);
}

fn do_something_with_person<P: Person>(p: P) {}

我希望上面的代码可以编译,但没有。

相反,我得到:

error: the trait `Person` is not implemented for the type `<<C as Catalog>::Dir as Directory<<C as Catalog>::Per>>::Per` [E0277]

AFAICT,这意味着编译器无法确定 person 变量是否具有 Person 特征。

我正在使用以下 rustc 版本:

rustc 1.2.0-dev (a19ed8ad1 2015-06-18)

我错过了什么吗?

最佳答案

这里是更正:

pub trait Directory<P: Person> {
type Per : Person = P;
fn get_person(&self) -> Self::Per;
}

Directory 中的类型Per 可以在特征实现中重新定义。编译器不知道Self::Per(实现中重新定义的Per)是否实现了traitPerson,所以你必须绑定(bind)它来实现 Person

关于rust - 特征和关联类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31243253/

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