🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.arch
Article #55

Re: Optimization by programmers

#55
From: Dan Cross
Date: Mon, 12 Oct 2026 15:41
238 lines
9845 bytes
In article <1791742457-5857@newsgrouper.org>,
MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
>
>Terje Mathisen <terje.mathisen@tmsw.no> posted:
>
>> Dan Cross wrote:
>---------
>> 
>> My old asm/C brain _knows_ that a slice of something with a known 
>> address and total length is effectively the same thing as an unmutable 
>> array.
>
>Can I get a definition of what mutable in Rust means ??

First, it is important to note that this is a logical concept,
and has no bearing on the physical properties of the computer
that the program is running on.

>Intuition would imply the inverse of opposite of const from C.

Here's a detailed explanation.

By default, variables in Rust are immutable; that is, their
value may not change.  For example, one cannot assign to them,
and to try and do so is a compile-time error:

?	let foo = something();
?	foo = something_else();	// Error: `foo` is immutable.

"Mutable", then, means the opposite: the value _can_ change.
Mutability is intorduced via the `mut` keyword:

	let mut foo = something();
	foo = something_else();	// Ok: `foo` is mutable.

In Rust, this extends to references, which have specific
properties: references are non-nullable, and can only refer to
valid, initialized objects; references are also prohibited from
outliving the object they refer to, and furthermore, they carry
a notion of mutability themselves: a mutable reference can be
used to change its referrent; immutable references cannot.
Immutable references are created using the `&` operator; mutable
references use the `&mut` operator.

Importantly, while immutable references can be created to
mutable objects, the inverse is not true: mutable references
cannot be created to immutable objects.  So, for example this
does not compile:

?	let foo = something();
?	let foomut = &mut foo;	// `foo` is immutable

But this is ok:

	let mut foo = something();
	let foomut = &mut foo;

As is this:

	let mut foo = something();
	let fooref = &foo;	// Immutuable reference
	let barref = &foo;	// Ok; immutable reference

Having multiple immutable references to an object is fine, but
the language requires that _mutable_ references to an object
are mutually exclusive with any other reference to that object.
In Rust, we say that we "borrow" a reference to an object, and
the compiler has a thing called, "the borrow checker" that
checks that all of these properties hold.

So this will fail to compile:

?	let mut foo = something();
?	let foomut = &mut foo;	// Ok: only mutable
?	let barmut = &mut foo	// Fail: a mut ref to foo exists

As will this:

?	let mut foo = something();
?	let foomut = &mut foo;	// Ok; only reference.
?	let fooref = &foo;	// Fail: a mut ref to foo exists

And as will this:

?	let mut foo = something();
?	let fooref = &foo;	// Ok: immutable reference.
?	let barref = &foo;	// Ok: multiple immut. refs ok
?	let foomut = &mut foo;	// Fail: exiting ref already

References also have a property called a "lifetime" that is tied
to the object they are borrowed from; the rule is that a
reference is not allowed to outlive its referrent.  So this,
again, is a compile time error:

?	let foo = {
?	    let bar = something();
?	    &bar		// Error; bar going out of scope
?	};

Here, I created a new scope (indicated by the curly braces) and
bound some object to the name `bar` in that scope, and attempted
to preserve a reference to that object outside of that scope.
However, that object only exists in that scope, so when the
scope ends, so too does the lifetime of the object; trying to
use a reference to it beyond that point violates the life time
rules enforced by the borrow checker.

But this serves to introduce another aspect of this, which is
that scopes and lifetimes matter with respect to how the
compiler treats these rules.

Take the following:

	struct Obj(u32);	// Tuple struct containing a u32
	impl Obj {
	    fn print(&self) {
	        println!("Value in obj is: {}", self.0);
	    }
	}

Here, I have defined a trivial struct (a "tuple struct"
specifically) that contains a simple datum; an unsigned 32-bit
integer.  And I have written an "implementation" of that type
that provides a "print" method that takes `&self`; that is,
takes an immutable reference to an instance of that object and
prints the integer.

Now, consider this code:

	let mut foo = Obj(42);
	foo.print();
	let foomut = &mut foo;
	foomut.print();

What should happen here?  The first three lines are fine; I
create the object, and I invoke its `.print()` method, which
takes an immutable reference to `foo`, and then I borrow a
*mutable* reference to foo, which is fine (the immutable
reference that `.print()` borrowed is gone at that point).

But in the 4th line I try to invoke `.print()` through through
the mutable borrow.  However, as we have seen, `.print()` takes
an immutable reference, and I'm clearly holding a *mutable*
reference, which appears to violate the borrowing rules.
However, this code compiles just fine: what happened?

As it turns out, the compiler allows a mutable reference to be
_coerced_ into an immutable reference, which is what is
happening here.  The compiler is allows this since it can infer
that nothing else can take an mut reference to the original
object while the mut ref exists, and since the mut ref is in
use, nothing can indirect through it and modify the underlying
object.   So things like this are fine:

 0      fn scopes() {
 1	    let mut foo = Obj(42);
 2	    foo.print();
 3	    let foomut = &mut foo;
 4	    foomut.print();
 5	    foo = Obj(32);
 6	    foo.print();
 7	    let barmut = &mut foo;
 8	    barmut.print();
 9	    barmut.0 = 22;
10	    foo.print();
11	}

This also illustrates a couple of other aspects of the type
system: moves and non-lexical lifetimes.

Prior to 2018, the lifetimes of Rust objects followed the
lexical scopes of those objects, and this code would have failed
compilation on line 10, since the `&mut barmut` mutable borrow
from `foo` still existed in the lexical scope where we called
`foo.print()`.  But since 2018, the borrow checker was changed
so that lifetimes reflect the flow graph of the program, not
just the lexical structure; in this case, the compiler can infer
that nothing in the program uses `barmut` after line 9, so
calling `foo.print()` on line 10 is fine; the borrow still
"exists" but is inactive by then.

On the other hand, if I rewrite the last few lines as:

?	foo = Obj(32);
?	let barmut = &mut foo;
?	foo.print();
?	barmut.0 = 22;
?	barmut.print();

Then this fails to compile; the immutable borrow taken for
`foo.print()` conflicts with the mutable borrow taken on the
previous line.

By default, all assignments in Rust have _move_ semantics: after
the assignment, the source is considered destroyed, and any
references to it are no longer valid.  That's why one can assign
to `foo` and on line 5 and then take a mut reference to it on
line 7; the assignment on 5 implicitly dropped the original
`foo` object created on line 1 and replaced it with a new
object, so the mut reference it created on line 3 is invalid;
an attempt to use it subsequently would fail to compile.

One can define a `copy` operator for types that should not have
move semantics; this is usually applied to trivial types (like
integers).

One may ask, "why bother with all of this stuff?" and the answer
is that Rust is designed for a multicore world.  There is one
other wrinkle here that gives Rust a lot of power, and that's
how all of this stuff interacts with data races: safe Rust code
is data race free.

Rust does not mandate a particular shape or type of (software)
thread, but because of the "mut ref ^ immut ref" rule, enforced
by the borrow checker at compile-time, safe Rust programs cannot
race on access to data, even in the face of multithreading.

Rust handles this by exposing two "marker traits", `Sync` and
`Send`. To quote the _Rustinomicon_, "A type is `Send` if it is
safe to send it to another thread" and "A type is `Sync` if it
is safe to share between threads (T is `Sync` if and only if
`&T` is `Send`)."  That is, a type can be _shared_ between
threads if it is safe to send an immutable reference to it from
one thread to another, and the compiler can check borrows
against the lifetimes of objects, hence, can detect data races
_statically, at compile time_.
(https://doc.rust-lang.org/nomicon/send-and-sync.html)

Those of us familiar with writing multithreaded programs will
recognize the power of these constructs: these rules, taken
together, statically eliminate entire categories of common
memory and concurrency problems.

Anyway, that what "mutable" means, in a nutshell, and why it is
important.

	- Dan C.
Technical Details
Message-ID: <11aiv39$bpk$1@reader2.panix.com>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mail
References: <1177fdi$26ea4$1@dont-email.me> <11a6870$41j$1@reader2.panix.com> <11a6a6h$37i1n$1@dont-email.me> <1791742457-5857@newsgrouper.org>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mail
From: cross@spitfire.i.gajendra.net (Dan Cross)
Newsgroups: comp.arch
Subject: Re: Optimization by programmers
Date: Mon, 12 Oct 2026 15:41:29 -0000 (UTC)
Organization: PANIX Public Access Internet and UNIX, NYC
Message-ID: <11aiv39$bpk$1@reader2.panix.com>
References: <1177fdi$26ea4$1@dont-email.me> <11a6870$41j$1@reader2.panix.com> <11a6a6h$37i1n$1@dont-email.me> <1791742457-5857@newsgrouper.org>
Injection-Date: Mon, 12 Oct 2026 15:41:29 -0000 (UTC)
Injection-Info: reader2.panix.com; posting-host="spitfire.i.gajendra.net:166.84.136.80";
	logging-data="12084"; mail-complaints-to="abuse@panix.com"
X-Newsreader: trn 4.0-test77 (Sep 1, 2010)
Originator: cross@spitfire.i.gajendra.net (Dan Cross)