Puzzle 16: Explanation
Let's learn how function overloading and variable overloading works in Rust.
We'll cover the following...
Test it out
Hit “Run” to see the code’s output.
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:
#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 ...