gpt4 book ai didi

rust - 有没有办法制作包含自身矢量的特征?

转载 作者:行者123 更新时间:2023-11-29 08:17:54 25 4
gpt4 key购买 nike

我对 rust 很陌生,我有以下问题:我想拥有我称之为 Artifact 的特征,Artifact 的定义是它可以包含多个 Artifact

我的第一个想法是制作一个包含 Artifact 特征向量的 Artifact 特征:

trait Artifact
{
type artifacts = Vec<Box<dyn Artifact>>;
}

我收到以下错误:

error[E0191]: the value of the associated type `artifacts` (from the trait `Artifact::Artifact`) must be specified
--> src/Artifact.rs:4:30
|
4 | type artifacts = Vec<Box<dyn Artifact>>;
| -------------------------^^^^^^^^^^^^---
| | |
| | associated type `artifacts` must be specified
| `artifacts` defined here

有没有办法在 rust 中进行这种设计?

最佳答案

如果您将特征中的类型定义定义为dyn trait,那么它是一个关联类型,您需要在该特征的实现中指定该类型。

Is there a way in rust to make this kind of design?

在当前的稳定版本 channel 中,不支持默认关联类型。但是您可以通过如下每晚发布 channel 实现您的需求:

#![feature(associated_type_defaults)]
trait Artifact {
type artifacts = Vec<Box<dyn Artifact<artifacts = Self>>>;
}

Playground


稳定发布 channel 中,您可以实现最接近的想法,如下所示:

trait Artifact {
fn artifact_call(&self);
}

struct Artifact1 {
inners: Vec<Box<dyn Artifact>>,
}

struct Artifact2;
struct Artifact3;

impl Artifact for Artifact1 {
fn artifact_call(&self) {
self.inners
.iter()
.for_each(|artifact| artifact.artifact_call());
}
}

impl Artifact for Artifact2 {
fn artifact_call(&self) {
println!("Artifact 2 Call");
}
}

impl Artifact for Artifact3 {
fn artifact_call(&self) {
println!("Artifact 3 Call");
}
}

fn main() {
let container_artifact = Artifact1 {
inners: vec![Box::new(Artifact2), Box::new(Artifact3)],
};
container_artifact.artifact_call();
}

Playground

关于rust - 有没有办法制作包含自身矢量的特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56334972/

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