如何按嵌套结构中的字段对向量进行排序?

时间:2021-04-06 00:05:29

标签: sorting struct rust

我可以对 Vec<Answer> 进行排序,但我需要按嵌套结构体中的字段 place 进行排序。

#[derive(Debug)]
struct Reply {
    final_text: String,
    structure: Vec<Answer>,
}

#[derive(Debug)]
struct Answer {
    place: u8,
    text: String,
}

fn main() {
    let a1: Answer = Answer {
        place: 1,
        text: String::from("test_text"),
    };
    let a2: Answer = Answer {
        place: 2,
        text: String::from("test_text"),
    };
    let a3: Answer = Answer {
        place: 3,
        text: String::from("test_text"),
    };

    let mut r: Reply = Reply {
        final_text: String::from("another_text"),
        structure: vec![a1, a2, a3],
    };

    r.sort_by_key(|a| a.structure.place);

    println!("{:?}", r);
}

我收到一个错误:

error[E0599]: no method named `sort_by_key` found for struct `Reply` in the current scope
  --> src/main.rs:32:7
   |
2  | struct Reply {
   | ------------ method `sort_by_key` not found for this
...
32 |     r.sort_by_key(|a| a.structure.place);
   |       ^^^^^^^^^^^ method not found in `Reply`

据我所知,我需要做一些类似的事情:

impl Reply {
    fn sort_by_key(???) {
        ?????????
    }
}

如何在嵌套结构上实现排序?

1 个答案:

答案 0 :(得分:2)

正如我在评论中被告知的那样,我错了:

r.sort_by_key(|a| a.structure.place);

正确的代码是:

r.structure.sort_by_key(|a| a.place);

非常感谢您的帮助!