gpt4 book ai didi

rust - 许多结构的一个特征的类似实现

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

在下面的代码中,唯一不同的是 println! 的实现。

感觉应该有办法让我不必写出两个完全不同的实现,但是我没有找到办法。

pub trait ChangeDecision{
fn change_decision(&mut self);
}

impl ChangeDecision for Hero{
fn change_decision(&mut self){
self.should_change_decision = false;
let rand_num = rand::thread_rng().gen_range(1, 101) as f32 / 100.;
let mut prob_counter = 0.0;
for (action, prob) in &mut self.decisions.iter(){
prob_counter += *prob;
match prob_counter{
p if rand_num > p => {},
_ => {println!("{}: {:?}", self.name, action); self.current_decision = *action; break},
}
}
}
}

impl ChangeDecision for Team{
fn change_decision(&mut self){
self.should_change_decision = false;
let rand_num = rand::thread_rng().gen_range(1, 101) as f32 / 100.;
let mut prob_counter = 0.0;
for (action, prob) in &mut self.decisions.iter(){
prob_counter += *prob;
match prob_counter{
p if rand_num > p => {},
_ => {println!("{:?}: {:?}", self.side, action); self.current_decision = *action; break},
}
}
}
}

当实现完全相同时,我可以使用宏来实现两者。即

macro_rules! impl_SimilarStuff {
($T:ident) => {
impl SimilarStuff for $T{
fn my_func(&mut self){
true
}
}
}
}

impl_SimilarStuff!(ThingOne);
impl_SimilarStuff!(ThingTwo);

但是我找不到任何“宏观条件”的例子

最佳答案

我处理这个问题的方法是使用另一个特征来处理不同的部分。像这样的东西:

trait PrintSomething {
fn print_something(&self, action: Action);
}

impl PrintSomething for Hero {
fn print_something(&self, action: Action) {
println!("{}: {:?}", self.name, action);
}
}

impl PrintSomething for Team {
fn print_something(&self, action: Action) {
println!("{}: {:?}", self.side, action);
}
}

// Now the macro would expand to:
impl ChangeDecision for Hero {
fn change_decision(&mut self){
self.should_change_decision = false;
let rand_num = rand::thread_rng().gen_range(1, 101) as f32 / 100.;
let mut prob_counter = 0.0;
for (action, prob) in &mut self.decisions.iter(){
prob_counter += *prob;
match prob_counter{
p if rand_num > p => {},
_ => {
self.print_something(action);
self.current_decision = *action;
break
},
}
}
}
}

关于rust - 许多结构的一个特征的类似实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38541122/

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