-
I was doing the fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
words.iter().map(|word| capitalize_first(word)).collect()
} which is the right solution. Then, I write fn capitalize_words_string(words: &[&str]) -> String {
words.iter().map(|word| capitalize_first(word)).reduce(|a, b| a + &b).unwrap()
} which also works fine. Out of curiosity, I looked at the solution and find out that fn capitalize_words_string(words: &[&str]) -> String {
words.iter().map(|word| capitalize_first(word)).collect() which is exactly the same as |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
I am by no means a rust expert, but here is my best attempt at an explanation. If you look at the implementation of the Basically, the Hint: you'll notice that the Hopefully that answers your question, feel free to ask more! |
Beta Was this translation helpful? Give feedback.
-
Thanks @frroossst for your reply. It makes it definitely more clear (I also read the |
Beta Was this translation helpful? Give feedback.
-
Also, here is a simple example to further illustrate what generics do fn larger<T: PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
fn main() {
let x = 5;
let y = 10;
let result = larger::<i32>(x, y);
// let result = larger::<i32>(x, y);
println!("The larger value is: {}", result);
let s1 = "apple";
let s2 = "banana";
let result_str = larger::<&str>(s1, s2);
// let result_str = larger::<&str>(s1, s2);
println!("The larger string is: {}", result_str);
} the larger function is generic, meaning it can work for multiple data types, in this example it works for both But to answer your question. I think a lot of knowing which method to use comes from writing code. Suppose you have never had to use the The more you use something the more likely you are to remember how to use it and what to use to solve your problem. apologies for the long answer, hope it helped. |
Beta Was this translation helpful? Give feedback.
-
That's super useful, thanks you. Especially the possibility to suggest the specific type to use for the generics. |
Beta Was this translation helpful? Give feedback.
I am by no means a rust expert, but here is my best attempt at an explanation.
If you look at the implementation of the
.collect()
in iterator ref, you'll notice a<B>
in the function definition, which means it is a generic. You can learn more about generics here.Basically, the
collect()
method is implemented forVec<String>
andString
and for many other types. So, when yo do thecapitalize_words_vector
the compiler infers that the variant of the collect method to be used must be the one that returnsVec<String>
and in the functioncapitalize_words_string
would use the variant or version of the collect method that returns the typeString
Hint: you'll notice that the
reduce
method is also…