How is the Index/Add/Deref/etc traits able to enable new syntax?

Sorry if I am a bit dull, but what is happening to enable traits to relate to syntax, such as index notation? (v[0])

I assume that the same mechanism is enabling dereferencing via the unary * and addition the binary + operator.

These traits are defined in the standard library, and have a magical #[lang] attribute applied: https://github.com/rust-lang/rust/blob/master/src/libcore/ops.rs#L243.

This attribute tells the compiler that this trait should use to desugar certain syntax into method calls.

2 Likes

Wow, that was quick. Thanks!

Just in case anyone is looking for an answer to "so, which lang attributes are currently supported?", the Language Items section of the Rust Reference is probably a fairly good place to look.

At the moment, it doesn't look like there's anything definitive:

The set of language items is currently considered unstable. A complete list of the built-in language items will be added in the future.

There is a project going on at

https://github.com/rust-lang/rust/issues/38643

This includes filling out the reference. Help is definitely welcome.

Lang items explained: Rust Tidbits: What Is a Lang Item? - In Pursuit of Laziness