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?
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.
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.
Eiffel or Smalltalk are two languages, among others I could chose from, where primitives and others types are differently implemented, yet unless you dive into the nitty gritty details, they look exactly the same to the developer as the compiler handles them exactly the same, and there are no extension methods to be seen.
However, it would be impossible to implement a #toggle method in Smalltalk that behaves like this, because you're calling it on the singleton True (or False) object; Smalltalk local variables, like Lisp variables, are references to objects rather than objects themselves.
(You obviously know this, but it might be a surprise to many people reading this thread.)
Go is fine with pointer methods (comparable to Rust &mut self) on types that are structurally "primitives". (Go predeclared types do not have methods.)
package main
import "fmt"
type T int32
func (t *T) inc() { *t = *t + 1 }
func main() {
var t T = 42
t.inc()
fmt.Println(t)
}
Primitive types and composite types having the same capabilities is a bit of a value statement for C++ and Rust IMO, and it's missing in a lot of languages downstream (IMO) of the "every variable is a reference to a slot/pointer" philosophy taken by most every managed language
C++ doesn't have methods/ "member functions" on the primitive types.
One reason is that C++ doesn't know where to put them, for user defined class, struct or union types these "member functions" as their name suggests live inside the class/ struct/ union definition but for a primitive where would these live?
In Rust they're just impl blocks, for example the method we're discussing here is:
And I think there's a decent chance that it never will, at least in the form it has been proposed in in the past (i.e., member function syntax being effectively turned into free function calls). P3027 "UFCS is a breaking change, of the absolutely worst kind" [0] argues quite strongly that that particular form of UFCS is basically completely broken.
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 think 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.
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.
Not quite; the method uses `&mut self`, so it actually operates on a mutable reference to the value that happens to be a primitive. If you declare a boolean without specifying the binding as mutable, you'd get a compiler error from trying to call this method. Moreover, if anything else had a reference to it at the same time, it would also cause a compiler error to call this method.
This is definitely something that Rust does a bit different than most other languages, but it's not anything specific to this method, booleans, or particularly new to the language. Most people will learn about the common different ways of defining a method (via ownership, shared reference, or mutable reference) fairly early on in programming Rust.
Think of having the method for AtomicBool, where you are forced to call methods for all value accesses. `atomic_bool.toggle(Ordering::SeqCst)` would read much better than `atomic_bool.fetch_xor(true, Ordering::SeqCst)`.
I think a major issue in all OOP languages is determining which operation mutates and which does not, and often having both operations, or even worse, if there's a third, static method. This is redundant and creates opportunity for code style divergence.
An example would be having both `Vector3.Add` and `Vector3.AddToSelf` instance methods as well as third `Vector3::Add` which takes two Vector3s.
What may be surprising to you coming from other languages, is that primitive types in Rust have their own methods! So methods applying to primitives is not unusual at all in Rust.
Most (not all) static & ahead-of-time compiled languages. C++ and Java come to mind. Method calls on built-in primitive types is more of a dynamic language thing (think: ruby, python) that got extended into compiled languages in recent memory.
Is x = !x faster than x.toggle() because from my naked eyes no function is called? Or does the compiler know that the function toggle should be replace with `!=`? If the compiler does know that, how is that knowledge implemented? Is there a table of special functions that should be replaced with something else? Or some more clever way?
The LLVM backend used by Rust is jokingly said to have a inlining heuristic of "yes" ie it will always try to inline everything because that's usually faster.
I'll go out on a limb and hypothesize that there are going to be much larger difference between debug and release mode for any non-trivial code that the overhead of `toggle` in debug mode will quite literally never end up mattering to anyone in practice.
Looks like part of the motivation was for things with long names like `some_struct_a.some_field_b.some_subfield_c`, where needing to name the field twice would have pushed people to using `^= true` instead, which is a bit more roundabout to decipher and risks people forgetting the idiom and writing `^= false` by accident. Not necessarily the most useful API, but not unmotivated and harmless to add.
When a similar thing was introduced to Swift it too raised a lot of heated discussions. Somehow, people became extremely passionate about this little extension.
Fast forward to today. After years of using it I find it very good for readability. It became the default in codebases. Nobody complains anymore and absolutely no one is confused.
No, these aren't equivalent: the second line mutates the iterated-over values, while the first doesn't. And the first line returns an iterator over bool, while the second returns an iterator over ().
If you have a (&mut) reference it would actually be x = !x. Also toggle is a function that can be passed to higher order functions without needing a lambda. For example, if you have a boolean in an option you can do opt.iter_mut().for_each(book::toggle). Or similar if you had a collection of booleans.
But under the hood it's all the same https://doc.rust-lang.org/stable/src/core/bool.rs.html#157-1...