Please help with generics

I’d like to note that while writing code generic over numeric types in Rust is possible, its cumbersomeness means that it’s not the simplest thing to do, so maybe it’s not the nicest exercise for learning Rust, especially at a beginner level. If you’re just learning about generics and simple traits, you might at least want to postpone it for later.

Any nontrivial function that’s supposed to be generic over numeric types quickly involves a large number of trait bounds, or it requires you to study and use traits and API of additional crates such as num (or you could also write your own trait and a bunch of implementations, but that might in turn become cumbersome - if you want to support all primitive numeric types - or involve using macros). Fortunately, generic functions over numeric types aren’t necessary in too many situations anyways.


Three more little remarks as you’re learning Rust and I noticed in your code:

  • If you like, you can use the “relatively” new println!("The result is {res}"); syntax which can be slightly less cumbersome to type and read. I though I’d mention it, because it might not have made its way into the book yet.

  • Also, I recommend using clippy when writing code. It suggests useful things such as

    warning: unneeded `return` statement
      --> src/main.rs:10:5
       |
    10 |     return first + 5;
       |     ^^^^^^^^^^^^^^^^
       |
       = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return
       = note: `#[warn(clippy::needless_return)]` on by default
       = help: remove `return`
    

    While you wouldn’t have gotten this feedback from clippy on your code in particular, as it doesn’t compile successfully in the first place, it teaches a few useful patterns and you would’ve probably already come across suggestions to remove unnecessary returns (and maybe also other things) if you used it.

    I commonly like to configure my IDE to use cargo clippy instead of cargo check, and I also like to use a code-watching tool such as bacon (after installation invoked to use clippy with bacon clippy) in a second window for convenient display of full error messages while writing code.

  • Finally, it’s useful to use rustfmt (via cargo fmt, or e.g. via the “Rustfmt” button under “TOOLS” in the playground to format code you submit on a forum, since a standard formatting style improves readability.

5 Likes