rustlings
rustlings copied to clipboard
generics1: does not require use of explicit generics
The idiomatic solution for generics1 is to simply remove the explicit type from the variable binding since it can be inferred:
fn main() {
let mut shopping_list = Vec::new();
shopping_list.push("milk");
}
The hint says:
Vectors in Rust make use of generics to create dynamically sized arrays of any type.
You need to tell the compiler what type we are pushing onto this vector.
Two problems with this:
- The solution is better without specifying a type and thus is not teaching/requiring the explicit use of generics
- The hint is wrong, because there is not need to tell the compiler the type
I agree with you. Maybe the thought process at the time of writing was
- as a way of learning about generics without depending much on the compiler, or better phrased as to get the hang of the generic syntax
let mut shopping_list: Vec<&str> = Vec::new();
- and going of the reasoning, making one familiar to the explicit syntax, would make one more comfortable with the turbofish syntax in the future
Again, I do agree with you, but this is the conclusion I drew after reading generics1.rs.
I see two options here:
- Make it explicit, that this example is not showing the idiomatic solution
- Find a better example, where the use of generics is required. The challenge here is to find one that is simple enough, to not distract from the point being made
I'd lean towards the latter option myself.
Find a better example, where the use of generics is required. The challenge here is to find one that is simple enough, to not distract from the point being made
I agree with this too
Hi, I found this example of generics and the turbofish operator.
// generics
fn get_default_value<T>() -> T
where
T: Default,
{
Default::default()
}
fn main() {
let number_default_value = get_default_value::<i32>();
println!("Default value of i32: {}", number_default_value);
}
I would like to get you guys's opinions. I'm not sure on this because it uses the where clause.
I rewrote the exercise in the upcoming version 6: https://github.com/rust-lang/rustlings/blob/v6/exercises/14_generics/generics1.rs