通过迭代而不是使用.push()来填充结构元素的向量

问题描述 投票:1回答:1

[我试图找到一种优雅的方法来用循环或逻辑填充结构元素的向量,而不是为我创建的每个元素写一个.push()

struct元素是一个比以下示例更多字段的问题,并且实例是可变的,因为它们由用户输入修改:

struct Question {
    id: usize,
    question: String,
}

fn some_fn() {
    //A large and growing list of questions
    let mut q0 = Question {
        id: 0,
        question: String::from("Q0"),
    };
    //  .
    //  .
    //  .
    let mut q100 = Question {
        id: 100,
        question: String::from("Q100"),
    };

    let length: usize = 100;

    let mut w: Vec<String> = Vec::new();
    for a in 0..length {
        let s = format!("q{}", a);
        w.push(s);
    }
    //w contains ["q0", "q1", ..., "q100"] but is of type std::string::String

    let mut v: Vec<&mut Question> = Vec::new();
    //Expects type struct `main::Question`

    //I would like to avoid :
    v.push(&mut q0);
    v.push(&mut q1);
    //  .
    //  .
    //  .
    v.push(&mut q100);
}

我不确定在我的示例中w: Vec<String>是否有用。

我研究了.collect(),但不了解在我的情况下如何使用它。

如果这是我没有找到的副本,我很乐意指出一个类似的问题。

vector rust
1个回答
0
投票

如果可以使用函数生成Question对象,则可以使用迭代器。 Here是一个示例,该示例仅生成数字范围之外的已编号Question对象:

struct Question {
    id: usize,
    question: String,
}

fn main() {
    let v: Vec<Question> = (0..10)
        .map(|x| Question {
            id: x,
            question: "Q".to_string() + &x.to_string(),
        })
        .collect();

    for x in &v {
        println!("{}: {}", x.id, x.question);
    }
}

Here是从字符串数组中获取字符串的示例:

struct Question<'a> {
    id: usize,
    question: &'a str,
}

const QUESTIONS: [&str; 3] = ["A", "B", "C"];

fn main() {
    let v: Vec<Question> = (0..questions.len())
        .map(|x| Question {
            id: x,
            question: questions[x],
        })
        .collect();

    for x in &v {
        println!("{}: {}", x.id, x.question);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.