Double Double

We'll cover the following...

Traits show up so much in Rust that we’ve already mentioned them multiple times in our previous lessons. It’s time to finally dive into this topic. We’ll start off with some simpler examples of traits. Then, we’ll get into some stronger motivation for using traits, focusing on some limitations we cleverly avoided with type parameters previously.

Let’s say I want to write a function that can double both i32s and i64s. I’m going to start off by using the ugly “add the type to the name” approach and end up with two functions:

Press + to interact
fn double_i32(x: i32) -> i32 {
x * 2
}
fn double_i64(x: i64) -> i64 {
x * 2
}
fn main() {
println!("double 5_i32 == {}", double_i32(5_i32));
println!("double 5_i64 == {}", double_i64(5_i64));
}

But I don’t like that at all! This feels like something that ...

Access this course and 1400+ top-rated courses and projects.