& symbol in the rust programming language

Hello, I'm starting to study rust, I'm not an expert in programming languages. when declaring a str variable, const MSG : &str = "hello"; we have a & before the str, what is the meaning of this &? I'm studying C in college, and in c language the & represents a reference to an address in memory.

When you have & before a type, it's reference. When you have it between two bools, then it's "and". When you have it in patterns, it would dereference the pointers that are being matched and borrow them. In this case, it's reference.
edit: I'm not so sure myself, so please refer to The Rust Reference.

1 Like

In this case, it means "a reference to the bytes stored in compiled binary". str itself is just a blob of bytes (with an additional requirement of being valid UTF-8), and it can be stored anywhere; in case of string literals, that's the executable file.

Note also that C "references" are more like Rust pointers; Rust references have an additional semantics, namely:

  • they're always views somewhere else - the data is stored elsewhere, in some place which owns it, the reference can't exist on its own;
  • therefore, they're always temporary;
    • two exceptions are static memory, like the aforementioned string literals, and leaked memory, explicitly forced to never being deallocated with something like Box::leak;
  • shared references (&something) require that the value inside cannot be mutated in any way;
    • the only exception is the case of &UnsafeCell<T> - in this case T can be mutated (but the UnsafeCell itself cannot);
  • unique references (&mut something) require that they're not aliased, i.e. while this reference exists, the value can't be reached in any other way.

For a basic understanding of the language, you should read The Book.

1 Like