paspielka
paspielka

Reputation: 75

Do Rust type annotations affect speed, or are they used just for readability's sake?

I'm learning Rust, and I have this question.

Is this

let x: i32 = 1;

Faster than

let x = 1;

Or is it just for readability?

Upvotes: 2

Views: 285

Answers (1)

James Williams
James Williams

Reputation: 779

You can investigate a compiled Rust program (that is, what the Rust compiler produces from Rust source code) easily using a tool such as Godbolt.

See the following example: https://godbolt.org/z/54x3Gd9oo

Godbolt compiler Rust image

As you can see, the compiled output is identical (as far as the arithmetic is concerned, the fact that the two functions are named differently introduces some minor differences). From this, you can infer that there is no speed advantage, and that the Rust compiler erases these details at compile time. It cannot have any effect on the wall time of the program being run, but as @Christina Sørensen says, it may affect compile time.

Upvotes: 4

Related Questions