Ushering out strlcpy()
Ushering out strlcpy()
Posted Aug 25, 2022 20:31 UTC (Thu) by tialaramex (subscriber, #21167)In reply to: Ushering out strlcpy() by NYKevin
Parent article: Ushering out strlcpy()
This won't be obvious to non-Rust people, and might not even be immediately obvious to new Rust programmers, but, in a sense all Rust's functions are/ can be written as free functions.
Here's some idiomatic Rust using a method call:
let mut news = "Linux Weekly News".to_owned();
news.replace_range(..5, "FreeBSD");
But while it isn't idiomatic in this case, you could also just write:
String::replace_range(&mut news, ..5, "FreeBSD");
As well as moving news to be the first parameter, we also need to write &mut to show that we want to pass the mutable reference, not move news itself into the replace_range function as a parameter. The method call sugar does that work for us by examining the signature of the String::replace_range function and seeing how the self parameter is used.
It really is just sugar, the code emitted will be identical (modulo perturbing an optimiser somewhere).
This is also how Rust resolves ambiguities. If Goose implements both AirlinePassenger and Bird but both traits define a fly() method, that's no problem in Rust, I can write:
if goose.is_wealthy() { AirlinePassenger::fly(&goose); } else { Bird::fly(&goose); }
In contexts where the code knows about Bird but not AirlinePassenger, goose.fly() is unambiguous and does what you expect, and likewise vice versa.
