【问题标题】:Efficient way to add values from multiple struct (RUST)从多个结构(RUST)添加值的有效方法
【发布时间】:2022-07-19 21:06:15
【问题描述】:

有没有一种有效的方法可以将多个结构中的字段值加在一起?

我正在学习 Rust,并尝试探索不同的方法和途径来获得更高效或更优雅的代码。

一个简单的方法是使用下面的代码,但是否有更好的方法?可能更深入地使用迭代器及其.map() 方法?我试过用它,但没有用。

fn create_bloc(name:String,value:u32) -> ControlBloc
{
    ControlBloc
    {
        name,
        value,
    }
}

fn main() {

    let vec_bloc = vec![
        create_bloc(String::from("b1"), 1),
        create_bloc(String::from("b2"), 2),
        create_bloc(String::from("b3"), 3),
        create_bloc(String::from("b4"), 4),
        create_bloc(String::from("b5"), 5),
        ];

    let mut count = 0;

    for ele in vec_bloc.iter()
    {
        count += ele.value;
    }

    println!("Count = {}",count);
}

感谢您的帮助!

【问题讨论】:

  • 你有明确的目标吗?如果不是,这可能更适合codereview.stackexchange.com
  • 我可以为您指出很多事情。 .iter()(由于自动取消引用,您可以使用它)。 .sum()。涡轮鱼。锈迹斑斑。 Playground。 Hf 学习 Rust。
  • @ChayimFriedman 我想只是尝试一些新的东西,没有什么特别的想法,但是如果我想修改方法,我可以扩展一些东西

标签: rust


【解决方案1】:

更惯用的方式:

struct ControlBloc {
    name: String,
    value: i32,
}

impl ControlBloc {
    fn new(name: String, value: i32) -> Self {
        Self {
            name,
            value,
        }
    }
}

fn main() {

    let vec_bloc = vec![
        ControlBloc::new(String::from("b1"), 1),
        ControlBloc::new(String::from("b2"), 2),
        ControlBloc::new(String::from("b3"), 3),
        ControlBloc::new(String::from("b4"), 4),
        ControlBloc::new(String::from("b5"), 5),
    ];

    let count = vec_bloc.iter().fold(0, |acc, x| acc+x.value);
    println!("Count = {}",count);
}

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 2019-06-01
    • 2021-12-15
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    相关资源
    最近更新 更多