Search⌘ K

Turbofish!

Explore how to guide Rust's compiler with the turbofish syntax to explicitly specify type parameters when multiple options exist. Understand its use in structs, functions, and standard library calls to prevent type inference errors and write clearer code.

We'll cover the following...

Let’s go back to fruit. We can write static methods just as easily as normal methods. Behold, my new fruit!

Rust 1.40.0
struct Fruit<T> {
apples: T,
bananas: T,
}
impl Fruit<i32> {
fn new() -> Self {
Fruit {
apples: 5,
bananas: 10,
}
}
}
fn main() {
let fruit = Fruit::new();
assert_eq!(fruit.apples, 5);
assert_eq!(fruit.bananas, 10);
println!("Success!");
}

Pop quiz: what’s the type of the fruit variable in main? Given that we have an impl block for a Fruit<i32>, it seems a fair guess that the type is Fruit<i32>. And you’d be right. But how did Rust know you wanted that? Why not give you a Fruit<String>? That’s because there was only one static method on Fruit available, called ...