It's a bit Rust question, but the type I used was anchor
's Vec<Pubkey>
type, so came here to ask. Here is the code.
pub fn set_tokens(&mut self, tokens: Vec<Pubkey>) -> Result<()> {
msg!("unsorted tokens: {:?}", tokens);
let mut sorted_tokens: Vec<_> = tokens.iter().collect();
sorted_tokens.sort();
msg!("sorted tokens: {:?}", sorted_tokens);
Ok(())
}
And the result is like this.
unsorted tokens: [1111111QLbz7JHiBTspS962RLKV8GndWFwiEaqKM, 1111111ogCyDbaRMvkdsHB3qfdyFYaG1WtRUAfdh, 11111112D1oxKts8YPdTJRG5FzxTNpMtWmq8hkVx3, 11111112cMQwSC9qirWGjZM6gLGwW69X22mqwLLGP, 111111131h1vYVSYuKP6AhS86fbRdMw9XHiZAvAaj]
sorted tokens: [1111111QLbz7JHiBTspS962RLKV8GndWFwiEaqKM, 1111111ogCyDbaRMvkdsHB3qfdyFYaG1WtRUAfdh, 11111112D1oxKts8YPdTJRG5FzxTNpMtWmq8hkVx3, 11111112cMQwSC9qirWGjZM6gLGwW69X22mqwLLGP, 111111131h1vYVSYuKP6AhS86fbRdMw9XHiZAvAaj]
It's totally same. Sort didn't happen. Why is it like this? And how could I fix it?
Pubkey
uses the default derivation forOrd
, which compares the array piece by piece: doc.rust-lang.org/std/cmp/… -- this is looking at the raw pubkey values, and not its base58 representation. If you want to sort the pubkeys by their base58 representation, you'll need to do something likesorted_tokens.sort_by(|a, b| a.to_string().cmp(b.to_string()));