gpt4 book ai didi

rust - 构造类型的向量并初始化它们

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

我正在尝试获得某种类型列表,然后我可以对其进行初始化并构建遗传算法。

问题是处理“类型”本身,我还没有找到获取类型数组并在每个类型上调用 ::new 以获得“实例”的正确方法。

// --- conditions.rs ----------------------------------
extern crate strum;
use strum_macros::{EnumIter}; // etc.

pub trait Testable {
fn new() -> Self;
fn test(&self, candle: &Candle) -> bool;
}

// use strum::IntoEnumIterator;
#[derive(EnumIter,Debug)]
pub enum Conditions {
SmaCheck,
CandlesPassed,
}

// simple moving average check
pub struct SmaCheck {
sma1: i8,
sma2: i8,
}

impl Testable for SmaCheck {
fn new() -> Self {
Self { sma1: 10, sma2: 20 }
}
fn test(&self, candle: &Candle) -> bool {
return true;
}
}


// --- generator.rs -----------------------------------
// creates random conditions, which will then be mutated and bred

use strum::IntoEnumIterator;
use crate::conditions::{Conditions, Testable};


pub fn run() {
for condition in Conditions::iter() {
println!("{:?}", condition); // this works

let testable = condition::new(); // undeclared type or module `condition`
println!("{:?}", testable::new());
}
}

最佳答案

您似乎有一个表示类型的枚举,以及一​​个与枚举变体同名的结构。

请注意,枚举变体名称与它们可能代表的任何类型无关。

此外,Rust 中不存在反射(不是 Java 意义上的),所以你不能有一个包含类型名称的值并从中创建该类型。

但是,可以取一个未知值的枚举(类型检查器无论如何都不能约束枚举值),并基于此枚举返回一个值。

此外,虽然方法可能不会直接返回未知类型,你可以使用 Box<dyn Trait>包装未知类型的值,或者创建一个枚举来实现特征并委托(delegate)给密封的实现。

以下可能更接近您想要的:

pub enum ConditionTypes {
SmaCheck,
CandlesPassed,
}

pub enum Condition {
SmaCheck(SmaCheck), // the first word is the enum variant, the second word is the type of the value it contains
CandlesPassed(CandlesPassed),
}

impl ConditionType {
pub fn new(&self) -> Condition {
match self {
Self::SmaCheck => Condition::SmaCheck(SmaCheck::new()),
Self::CandlesPassed => Condition::CandlesPassed(CandlesPassed::new()),
}
}
}

pub trait Testable {
// we don't really need new() in this trait, do we?
// if you want to use this trait when it could be of runtime-unknown type
// instead of compile-time generics, all methods must have a receiver.

fn test(&self, candle: &Candle) -> bool;
}

impl Testable for Condition {
fn test(&self, candle: &Candle) -> bool {
match self {
Condition::SmaCheck(inner) => inner.test(candle),
Condition::CandlesPassed(inner) => inner.test(candle),
}
}
}

// impl Testable for SmaCheck and CandlesPassed omitted

这看起来有点样板,但是有宏可以派生它。

关于rust - 构造类型的向量并初始化它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58480303/

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