rustlings icon indicating copy to clipboard operation
rustlings copied to clipboard

generics1: does not require use of explicit generics

Open benjaminbauer opened this issue 2 years ago • 5 comments

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:

  1. The solution is better without specifying a type and thus is not teaching/requiring the explicit use of generics
  2. The hint is wrong, because there is not need to tell the compiler the type

benjaminbauer avatar Mar 28 '23 15:03 benjaminbauer

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.

Eshanatnight avatar Apr 03 '23 06:04 Eshanatnight

I see two options here:

  1. Make it explicit, that this example is not showing the idiomatic solution
  2. 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

benjaminbauer avatar Apr 03 '23 07:04 benjaminbauer

I'd lean towards the latter option myself.

manyinsects avatar Apr 04 '23 07:04 manyinsects

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

Eshanatnight avatar Apr 12 '23 06:04 Eshanatnight

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.

Eshanatnight avatar Apr 17 '23 07:04 Eshanatnight

I rewrote the exercise in the upcoming version 6: https://github.com/rust-lang/rustlings/blob/v6/exercises/14_generics/generics1.rs

mo8it avatar Jun 27 '24 00:06 mo8it