(no title)
adregan | 4 months ago
Now apologies for the aside—and I know I'm likely wading into a very expansive topic and reducing it down to something simple—but why in Rust, if the types are known:
struct Song {
title: String,
artist: String,
rating: i64,
}
do you have to call `.to_string()` on things that look a lot like strings already? Song::new("Hate Me".to_string(), "Blue October".to_string(), 9)
Couldn't the compiler just do that for you?
LtdJorge|4 months ago
There is the exception of Deref. If the function requires type A, and you pass it type B, which Derefs into type A, the compiler will Deref it for you. But that is zero cost and panic free, whereas allocating (and copying) an owned type from a reference isn't. In Rust you have to be explicit.
Anyway, using String in function signatures is most often not the best choice. If you will internally be required to use a String, it's better to ask for a type "impl Into<String>", you'd call into() inside your function. And in the most common case, where you require a &str or can convert to your type from it, the best choice is an "impl AsRef<str>" and you can call as_ref() on it to get a str reference, which you can wrap in a Box, Rc, Arc, String, or your custom type, or pass it directly to other functions. All of those, Box<str>, Rc<str>, etc implement both traits.
Using impl Trait, you avoid having to declare generic parameters.
gnatolf|4 months ago
steveklabnik|4 months ago
tialaramex|4 months ago
On the other hand the String type is a growable array of bytes used to assemble strings, it's an owning type, so Song will own those two Strings, they can't go away or be altered via some other force. Owning a string would allow you to add to it, change it, or discard it entirely, you obviously can't do that to the text baked into the executable, so if you want to own a String it will have to be allocated at runtime.
You can also write "Some Words".to_owned() for example to the same effect.
estebank|4 months ago
https://groups.google.com/a/chromium.org/g/chromium-dev/c/EU...
rootnod3|4 months ago
When to use them is a whole different story. But examples of macros I like are `when` and `unless`. Yes, simple, but they show a nice example of their power.
For more complicated once, love it or hate it, but the `loop` macro is probably THE prime example of a powerful macro.
QuantumNomad_|4 months ago
It’s shorter to write and takes up a little less space on screen to. I almost always use .into() when like in your example I initialize String field members of a struct in Rust.
marcosdumay|4 months ago
If you don't see the gain, maybe Rust is not the right language for your use-case.
throwawaymaths|4 months ago