Why rust can not infer the result's type of collect()

why rust can not infer the result's type of collect()

Your code compiles fine when I type it out in the playground.

One thing that seems a bit suspect - in your code you have a let v and a type annotation, but the corresponding line in the error output doesn't display them. To the best of my knowledge, the error should show the entire line from start to finish, which makes me think your changes hadn't saved properly before the compiler ran.

Thank you

i had find the solution to this error . if i add the type annotation for v, it will work fine, but i do not understand why i need to add it, i think rust should infer it is Vec.

below code is error

String::from("12😇34").chars().map(|c| c).collect();

or

String::from("12😇34").chars().map(|c: char| c).collect();

collect can collect into other containers that implement FromIterator, of which Vec is just one particular container type. For example,

let v: HashSet<_> = String::from("12😇34").chars().map(|c: char| c).collect();

This is why the type annotation is necessary, so the compiler knows which FromIterator container you want. While some might prefer that collect return a Vec by default when no type is given, currently (to my knowledge) generics don't support the necessary defaults.

1 Like

got it

i understand it is rust can infer the container 's content is char , but it do not know that should put the char into which container, so it need i tell it

thank you

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.