Ushering out strlcpy()
Ushering out strlcpy()
Posted Aug 28, 2022 23:45 UTC (Sun) by KJ7RRV (subscriber, #153595)In reply to: Ushering out strlcpy() by tialaramex
Parent article: Ushering out strlcpy()
Is this the Rust equivalent of str.strip(" string with padding ")
as opposed to (" string with padding ").strip()
in Python?
Posted Aug 30, 2022 17:10 UTC (Tue)
by tialaramex (subscriber, #21167)
[Link] (1 responses)
It's very similar, however whereas self in Python is just a convention, self in Rust is a keyword, using it signals that you mean for this function to be a method, and so the type is implied. Not all functions implemented for a type in Rust have to be methods. Consider these two functions in the implementation of Goose:
fn is_wealthy(&self) -> bool { self.net_worth > 1000 }
fn is_healthy(goose: &Self) -> bool { self.hit_points > 90 }
The is_wealthy function can be used as a method, the self keyword means if I have a Goose named jimmy I can write:
if jimmy.is_wealthy() { println!("Swimming in money"); } else { println!("Aww, poor Jimmy"); }
But the is_healthy function is not a method, it's only an associated function. That capitalized word "Self" is also a keyword, but it just means "my type" and so we could have written Goose instead. So I always need to write:
if Goose::is_healthy(&jimmy) { println!("Feeling good"); } else { println!("Jimmy needs a goose doctor"); }
I believe this distinction does not exist in Python. The reason it is used in Rust is that sometimes a type exists mostly as a "pass through" for some other type, and so by having only associated functions instead of methods it is hidden from accidental method invocations. For example Rc and Arc are smart pointers offering reference counting, but they sport associated functions not methods, so that you need to say e.g. Rc::downgrade(&thing) and thus if thing.downgrade() already means something else the reference counted type doesn't get in your way.
Posted Aug 30, 2022 17:12 UTC (Tue)
by tialaramex (subscriber, #21167)
[Link]
fn is_healthy(goose: &Self) -> bool { goose.hit_points > 90 }
There is no "self" parameter on is_healthy because it isn't a method, and so the version I wrote above can't work since it refers to a self variable which doesn't exist.
Ushering out strlcpy()
OR
if Goose::is_wealthy(&jimmy) { println!("Swimming in money"); } else { println!("Aww, poor Jimmy"); }
Ushering out strlcpy()