Why Rust has name mangling

Take, for example, a program like this:

struct One;

struct Two;

impl One { fn foo() { ... } }
impl Two { fn foo() { ... } }

Now there are two functions named foo. But for historical reasons, each function is labeled with a single string for its name (in object files, executables and libraries, etc.). This string must be unique across all names in the entire program, including dependencies.

So rustc gives each function a different name by "mangling" foo into something like _ZN7example3One3foo17h16fcc82fa6043ccbE. Notice how the mangled name includes the crate name ("example"), the type and/or module the function is associated with ("One"), the bare name itself ("foo"), and a hash.

This means you can have a different foo for every combination of crate, module, type, and crate version, without collisions.

2 Likes