3 ms·
Constant is determined at compile time. It's constant over the every run of the same binary. Immutable is immutable for some specific span of time. In a simple
by GolDDranks 3y ago
Constant is determined at compile time. It's constant over the every run of the same binary.
Immutable is immutable for some specific span of time. In a simple case, like with Python immutable objects, it is constructed once, and after that, it never changes. With Rust, it's also possible for an object to be immutable while a reference to it exists and is passed to some function, but after that function call returns and the reference ceases existing, immutability ends.
- estebank 3y agoTo add to this, the following is valid: fn take_foo(x: Foo) -> Foo { let mut x = x; x.field = 0; x } The ownership semantics ensure that because there's a single owner of Foo at all times, it is always safe to make its binding mutable. This is different than trying to turn a &Foo into a &mut Foo, that's not allowed by safe Rust (and an undefined behavior minefield in unsafe Rust). For constants, you can think of them as a "stamp", whatever the value within the const gets inlined in the usage place in your code, every time. Immutability is about whether the value can be changed. To stretch the analogy, you can stamp a pattern on paper (const) but later doodle over it (mutability).