logoalt Hacker News

jacksontheel • yesterday at 9:58 PM • 3 replies • view on HN

I'm at a loss with the bool toggle method. Why would x = !x not be good enough?


Replies

stusmall • yesterday at 10:01 PM

You can. Something like toggle is nice because it is very clear at a glance. That's a subjective style call.

But under the hood it's all the same https://doc.rust-lang.org/stable/src/core/bool.rs.html#157-1...

➕ show 2 replies
IshKebab • yesterday at 10:06 PM

If you access the bool through a long path maybe.

  foo.bar().baz[expensive()].qux.toggle();
➕ show 2 replies
kibwen • yesterday at 10:06 PM

Proposal here: https://github.com/rust-lang/libs-team/issues/820

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.

➕ show 1 reply