Search⌘ K

Puzzle 16: Explanation

Explore how Rust differs from C++ by not supporting function overloading due to name mangling limitations. Learn how Rust generics allow creating flexible and reusable functions that work with multiple types while maintaining safety. Understand trait constraints that enable generic functions to operate correctly and how this design affects interoperability with C++ code.

Test it out

Hit “Run” to see the code’s output.

C++
fn double_it(n: i32) -> i32 {
n * 2
}
fn double_it(n: f32) -> f32 {
n * 2.0
}
fn main() {
println!("2 * 4 = {}", double_it(2));
}

Output

The program fails to compile, and we receive the following error message:


error[E0428]: the name "double_it" is defined multiple times

Explanation

In C++ and similar languages, redefining a function with different parameter types is known as function overloading. It allows us to provide similar functionality for multiple types without having to come up with a type-specific function name for each option. For example, the following is valid C++ code:

C++
#include <iostream>
using namespace std;
float double_it(float n) {
return n * 2.0;
}
int double_it(int n) {
return n * 2;
}
int main() {
cout << double_it(2);
return 0;
}

Function overloading works in C++ and not in Rust because of name mangling. When a function is compiled, a compiler-specific name for the function is created and used by the linker to connect function calls to actual memory addresses. In C++, mangled names include both the function name and the types of the ...