Flashcard Rust: Colon colon angle bracket or turbofish!
This confused me a lot when i started learning rust and the heading colon colon angle braket
is what I searched for first when I saw this syntax, but the official name of this syntax within the Rust community is turbofish.
What is it ?
It is to specify a concrete type, for a function, a struct, a method or an enum. The syntax of turbofish looks like:
::<T>
It looks kinda like a fish I guess, the name turbofish, check steve klabnik’s official explanation here for more details.
How is it used ?
Let’s take a simple example, to parse a string into float,
fn main() {
let pi_string = "3.1415";
let pi_float = pi_string.parse().unwrap();
println!("{}", pi_float);
}
This program will not compile as parse
function is too generic, and the rust compiler being helpful as always tell us to give a time annotation to the variable pi_float
:
.1.0 (/Users/unrahul/Coding/rust/learn/turbofish)
Compiling turbofish v0type annotations needed
error[E0282]: --> src/main.rs:3:9
|
3 | let pi_float = pi_string.parse().unwrap();
| ^^^^^^^^ consider giving `pi_float` a type
This can be solved in two ways, either we use a turbofish
notation for parse
function or use type annotation, let’s see how we can use turbofish
to solve this.
fn main() {
let pi_string = "3.1415";
let pi_float = pi_string.parse::<f32>().unwrap();
println!("{}", pi_float);
}
We tell the compile, which concrete type is being parsed using parse
, and the code compiles:
.1.0 (/Users/unrahul/Coding/rust/learn/turbofish)
Compiling turbofish v0+ debuginfo] target(s) in 0.21s
Finished dev [unoptimized /debug/turbofish`
Running `target3.1415
Lastly, let’s try the compiler suggested fix, that is to use type annotation:
fn main() {
let pi_string = "3.1415";
let pi_float : f32 = pi_string.parse().unwrap();
println!("{}", pi_float);
}
Yup, that works too!, as shown below:
.1.0 (/Users/unrahul/Coding/rust/learn/turbofish)
Compiling turbofish v0+ debuginfo] target(s) in 0.21s
Finished dev [unoptimized /debug/turbofish`
Running `target3.1415
References
End
This was a quick introduction to the turbofish notation and how it is used.