upvote
For someone who has decades of experience from other programming languages this does not look clear to me at all but rather confusing. Calling an method can change value of variable of primitive type?
reply
The big clue that'll jump out to any rust dev is the type signature:

pub const fn toggle(&mut self)

The "&mut" says that toggle takes a mutable reference to the instance it is called off of. This is also called a mutable borrow. You might thing that would get buried in the program because you don't always check the type signature of every method you call, but there are a few reasons that muts really jump out in rust. The languages immutable by default nature is one and the other is that several IDE have features to specifically draw attention to mutable instances/references. It's a fairly common pattern in rust to have helper methods on a type that take a mutable reference or ownership of self.

TL;DR: Rust's ownership model is very unique. Once it clicks its the cat's pajamas, but experience in other languages don't map well to this part of the language.

reply
When you call a method on something in Rust, the method gets passed that something (as a parameter called self). But the method gets to choose whether it's by move/copy or by reference. Here, toggle gets the bool passed by mutable reference.

In effect, if x is a bool, doing x.toggle() is rewritten by the compiler as bool::toggle(&mut x), which can of course modify x.

reply
There’s nothing special about primitives, they’re just types like any other. A method taking `&mut self` can always modify self, on any type. But you can only call such methods if the value is mutable to begin with, so it’s not really that interesting.

It’s only weird if you come from languages like Java where “primitives” are distinct from “objects”, which is a self-imposed limitation the language imposes.

reply
Or Go (also treats primitives rather specially) or roughly any language without extension methods (because primitives are at a minimum a pre-defined type). Which is quite a lot of languages really.

Otherwise agreed, methods like this can be mutable in any language that doesn't heavily specialize primitives.

reply
Why wouldn’t it be possible? The distinction in modern languages between primitive and not is an arbitrary one when it comes to stuff like this.
reply