gpt4 book ai didi

struct - 有没有一种方法可以基于特征实现创建结构?

转载 作者:行者123 更新时间:2023-12-03 11:44:27 24 4
gpt4 key购买 nike

我正在尝试使用一种方法的多个实现的结构:

trait Trait { fn apply(&self) -> vec<usize>; }

struct Bar<X> { vec: Vec<usize> }

impl<X> Bar<X> {
pub fn new(vec: Vec<usize>) -> Self { Self{vec} }
pub fn test(&self) {
// Things here
println!("Method: {:?}", self.apply());
// Things there
}
}

impl Trait for Bar<ThisWay> {
fn apply(&self) -> Vec<usize> { self.vec.iter().map(|x| x.pow(2)).collect() }
}

impl Trait for Bar<ThatWay> {
fn apply(&self) -> Vec<usize> { self.vec.iter().map(|x| x + 2).collect() }
}

fn main() {
Bar<ThisWay>::new(vec![1,2,3]).test();
Bar<ThatWay>::new(vec![1,2,3]).test();
}
哪个会返回:
>>> [1,4,9];
>>> [3,4,5];
我知道我可以创建2个以不同的方式实现这些方法的结构,但是这感觉很错误,因为它可能有很多冗余代码。
我也知道我可以引用该实现方法:
trait Trait { fn apply(vec: &Vec<usize>) -> Vec<usize>; }

impl Struct{
// fn new
test(&self, t: &impl Trait) {
// Things here
println!("{:?}", t::apply(&self.vec));
// Things there
}
}
struct ThisWay;
struct ThatWay;
impl Trait for ThisWay {fn apply(vec: &Vec<usize>) -> Vec<usize> {///} };
impl Trait for ThatWay {fn apply(vec: &Vec<usize>) -> Vec<usize> {///} };
fn main() {
let this_way = ThisWay{};
let that_way = ThatWay{};
let problem = Bar::new(vec![1,2,3]);
problem.test(&this_way);
problem.test(&that_way);
}
当我想在给定的struct中使用许多参数时,这种方法似乎不必要地复杂:
fn hill_climber(&self, nullary_op: &impl NullaryOperator, unary_op: &impl UnaryOperator, ...) {
self.vec = nullary_op();
self.vec = unary_op(&self.vec, self.n, self.m, self.jobs, self.stuff, ...);
}
这似乎是一种编写代码的被诅咒的方式。当方法实现不使用参数 m,而其他人使用该参数时会发生什么呢?

最佳答案

特性用于定义共享行为。在您的示例中,您想以不同的方式实现相同的特征。这违背了特质的目的。您可能应该具有两个特征,而不是像尝试的那样具有两个结构:

trait ThisWay {
fn apply(&self) -> Vec<usize>;
}

trait ThatWay {
fn apply(&self) -> Vec<usize>;
}
现在,您可以为您的结构实现这两个特征:
struct Bar {
vec: Vec<usize>,
}

impl ThisWay for Bar {
fn apply(&self) -> Vec<usize> {
self.vec.iter().map(|x| x.pow(2)).collect()
}
}

impl ThatWay for Bar {
fn apply(&self) -> Vec<usize> {
self.vec.iter().map(|x| x + 2).collect()
}
}
因为 Bar实现了 ThisWayThatWay,所以现在对 apply方法有两个定义。为了消除它们之间的歧义,我们必须使用完全合格的语法:
let this_bar = Bar::new(vec![1, 2, 3]);
println!("Method: {:?}", <Bar as ThisWay>::apply(&this_bar));

let that_bar = Bar::new(vec![1, 2, 3]);
println!("Method: {:?}", <Bar as ThatWay>::apply(&that_bar));
而且,正如预期的那样,您将获得两个不同的输出:
Method: [1, 4, 9]
Method: [3, 4, 5]

关于struct - 有没有一种方法可以基于特征实现创建结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64683645/

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