Meaning of the ampersand '&' and star '*' symbols in Rust

前端 未结 3 2024
既然无缘
既然无缘 2020-12-05 13:16

Despite thoroughly reading the documentation, I\'m rather confused about the meaning of the & and * symbol in Rust, and more generally about wh

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 13:54

    Using * to dereference a reference wouldn't be correct in C++. So I'd like to understand why this is correct in Rust.

    A reference in C++ is not the same as a reference in Rust. Rust's references are much closer (in usage, not in semantics) to C++'s pointers. With respect to memory representation, Rust's references often are just a single pointer, while C++'s references are supposed to be alternative names of the same object (and thus have no memory representation).

    The difference between C++ pointers and Rust references is that Rust's references are never NULL, never uninitialized and never dangling.


    The Add trait is implemented (see the bottom of the doc page) for the following pairs and all other numeric primitives:

    • &i32 + i32
    • i32 + &i32
    • &i32 + &i32

    This is just a convenience thing the std-lib developers implemented. The compiler can figure out that a &mut i32 can be used wherever a &i32 can be used, but that doesn't work (yet?) for generics, so the std-lib developers would need to also implement the Add traits for the following combinations (and those for all primitives):

    • &mut i32 + i32
    • i32 + &mut i32
    • &mut i32 + &mut i32
    • &mut i32 + &i32
    • &i32 + &mut i32

    As you can see that can get quite out of hand. I'm sure that will go away in the future. Until then, note that it's rather rare to end up with a &mut i32 and trying to use it in a mathematical expression.

提交回复
热议问题