Hacker Newsnew | past | comments | ask | show | jobs | submit | rauli_'s commentslogin

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.)


Yes, but that is orthogonal how primitives and reference types get exposed to the developer.

Something like toggle is also impossible in languages that favour immutability and forward progress requires creating new variables, like several functional and logic languages.


Agreed.

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)
    }

C++ lets you do this kind of stuff as well.

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:

    impl bool {    
        pub const fn toggle(&mut self) {
            *self = !*self;
        }
    }

Only because Unified Call Syntax is yet to land into the language, after several failed attempts.

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.

[0]: https://isocpp.org/files/papers/P3027R0.html


As WG21 goes, it is a matter of advocacy, persistency, and getting the required votes in the room, at least if the process doesn't change even with how C++26 contracts turned out to be.

I mean, sure, but that's basically a tautology since that's how everything made it into the standard into the first place. Those are necessary but not sufficient conditions.

I'm with you on this and would point at std::hive as an example of the results.

Not really, in first place it was basically CFront 2.0, alongside C++ARM akin to the K&R C book, with last minute addition of HP STL implementation.

The only piece that wasn't really available and was made in a waterfall design approach was export templates, with the known outcome that no one other than EDG has even bothered implementing it.

Post C++98 is when we got into the "advocacy, persistency, and votes" strategy.


You still needed "advocacy, persistency, and votes" to get stuff into C++98. It's just that some things need a lot more of the former to get the latter than others.

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.


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.

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 guess you're experiencing the feeling a mathematician gets when seeing a line like

x = x + 1


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.


In addition to what the sibling commenters have written, in order for this to compile, the variable would need to be declared as mutable.

> Calling an method can change value of variable of primitive type?

So long as the variable is mutable it's value can be changed


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.

    > decades of experience from other programming languages
What languages?

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.

I like that they used Comic Sans as font for the description.

That Web site thinks that my browser is an AI scraper for some reason.


As long as there are non-russian alternatives out there I'm never going to even try.


Or he just prefers GTK. I sure like it better than QT.


No person who has written software with both prefers GTK :D


I can still use and develop GTK2 software in Debian out-of-the-box, but not Qt3 or even Qt4.


Yes, because GTK2 is so difficult to upgrade to new versions, whereas Qt4 to Qt5 usually only involved replacing a few identifiers (cannot speak to Qt6 since I don't do Qt anymore). That's why distros need to drag GTK2 along even though we are already at GTK4.


I work on the IUP fork, where I have and support the Qt driver, which works with both Qt5 and Qt6, and I only need a couple of checks to make it work on both. I often check if I broke the Qt5 build; nope, all good there, hard to break. For GTK3 and GTK4, those must be separate drivers; there's no way you can handle that with a couple of checks. Everything is different. That was possible to some extent and works with GTK2/GTK3 (single driver), but there are so many checks and workarounds there. Qt is so nice to work with.


> so difficult to upgrade to new versions

Perhaps, because GTK developers insist, that GTK2, GTK3, GTK4 are different toolkits.

> Qt4 to Qt5 usually only involved ...

I'd start with Qt3 to Qt4.


Yeah let's start on a specific version that they overhauled the API since computers are getting new hardware features, god forbid a different DPI. And use that as a leverage point against a library that kept their API quite stable for the last 20 years!

Especially when comparing Qt against a library who couldn't keep its shit together for 5 years and is infamous for breaking all sorts of API and removing features.


> since computers are getting new hardware features

It's not possible to move forwards fast anywhere.

> and removing features

Yeah, this is indeed very unfortunate. They claim the GTK core team is about 2 devs, so tiny that we're lucky the development goes further at all. Hard to understand considering Red Hat became part of IBM.


He seems to completely ignore Ladybird project for some reason.


Lisp was meant to be written with M-expressions instead of S-expressions anyway.


For a brief period of time over 60 years ago, yes. :)


If you want a Lisp that basically has M-expressions, try Dylan. It even started with an S-expression syntax initially and then converted to infix.


M-expressions were never implemented and never used.


Actually, variations on M-expressions have been created many times in the Lisp world. (Look what you can do with macros!) So far, none of them has caught on. The latest attempt for Scheme is SRFI-266, which creates a very nice infix expression sublanguage. If I were working on a team, I would encourage them to use this, but I don't know if it has enough traction to become widespread.


It's a common mistake to think that the syntax of Lisps are a problem. People solving the supposed problem then discover it wasn't something that needed to be solved.


Haskell's syntax comes from ISWIM, which was motivated quite a lot by m-expressions.


Except in mathematica - which isn’t formally a lisp, but practically it’s used like one a lot of the time.


I actually created one for some time ago. It's nothing special but it has Vi keybindings.

https://github.com/RauliL/levite


This is brilliant! Thank you for creating it


Unchecked exceptions will eventually lead into programs crashing because some developer forgot to catch specific type of exception somewhere.


And developers never forget to check error codes.


Looking at code, it‘s easier to spot the missing check for an error code, than a not catched exceptions.

Also error codes are part of the signature of a function, which exceptions aren‘t.


If you need to wrap each call in try/catch, it's better to use return codes in some form or rethink the approach.


may I introduce you to the nodiscard attribute[1]?

  enum (class)? [[nodiscard]] Error {
    Ok,
    NoMem,
    ...
  };
[1]: https://en.cppreference.com/w/cpp/language/attributes/nodisc...



FWIW I’ve been using warn_unused_result in both gcc and clang since about 2020.


Yep, partial remedies are available for quite some time.


That seems like a better outcome than continuing when an error happened while thinking everything succeeded?


Yes, but that's not a dichotomy. Languages like Java have function declare what exceptions they throw, and the caller must either catch it or also declare that it throws it. Gets cumbersome quickly, but I believe it's for the best to encode exceptions at the type system.


In case you want to use React to make Web sites as well.


They should make a version of that runs as an app on a phone


They have one, it's called React Native Web Native


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: