如何处理生锈的这个基本错误?

how to deal with this fundamental error in rust?

im writing a program to convert a number to sorted reversed array of digits. eg : 23453 -> vec![5,4,3,3,2] but i got this error! and i cant fix this

error[E0599]: no method named `sorted` found for struct `Chars` in the current scope
    --> src/main.rs:2050:25
     |
2050 |   n.to_string().chars().sorted().map(|no| no.to_digit(10).unwrap() as u32).rev().collect::<Vec<u32>>()
     |                         ^^^^^^ method not found in `Chars<'_>`

error[E0277]: `Vec<u32>` doesn't implement `std::fmt::Display`

here is my code,

fn sorted_rev_arr(n : u32) -> Vec<u32>{
  n.to_string().chars().sorted().map(|no| no.to_digit(10).unwrap() as u32).rev().collect::<Vec<u32>>()
}

fn main(){
  let random_number = 23453;
  println!("the new number in array is {}",sorted_rev_arr(random_number));
}

can anybody help me to resolve this issue ?

Rust 迭代器或 Vec 中没有 sorted 方法。您必须先收集到 Vec,然后再对其进行排序:

fn sorted_rev_arr(n: u32) -> Vec<u32> {
    let mut digits = n
        .to_string()
        .chars()
        .map(|no| no.to_digit(10).unwrap() as u32)
        .collect::<Vec<u32>>();
    digits.sort();
    digits.reverse();
    digits
}

你也可以一次性做反向排序:

fn sorted_rev_arr(n: u32) -> Vec<u32> {
    let mut digits = n
        .to_string()
        .chars()
        .map(|no| no.to_digit(10).unwrap() as u32)
        .collect::<Vec<u32>>();
    digits.sort_by(|a, b| b.cmp(&a));
    digits
}

此外,您需要使用 {:?} 而不是 {} 来打印 Vec

Playground