【发布时间】:2020-11-04 16:07:44
【问题描述】:
我正在尝试使用具有多个实现一种方法的结构:
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);
}
当我想在给定结构中使用许多参数时,这种方法似乎不必要地复杂:
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 和其他使用参数?
【问题讨论】:
-
你想为
Bar<X>以外的任何东西实施Trait吗?如果没有,只需为X实现它,并让apply()采用&Bar而不是&self。
标签: struct rust traits implementation