What does the `#[lang = "..."]` attribute do?

Viewed 517

I'm reading the code at https://doc.rust-lang.org/1.56.0/src/core/str/mod.rs.html#120-122:

#[lang = "str"]
#[cfg(not(test))]
impl str {
...

and I can't find a reference to this attribute lang. Does it have something to do with declaring the structure of the primitive type str? And if so, where is the information dealing with the inner structure of str?

1 Answers

#[lang = "..."] defines a language item, which allows the Rust compiler to look up the item it is attached to and potentially add special behavior.

In the case of #[lang = "str"], the Rust compiler currently (as of October 2021) uses the str language item to collect methods defined on the str primitive so they can be looked up when called. The compiler also uses the str language item to prevent multiple inherent impls (in this case, impl str { ... }) from being defined for the str primitive.

Related