←back to thread

451 points birdculture | 4 comments | | HN request time: 0.484s | source
1. the__alchemist ◴[] No.43986975[source]
I seem to have eased into a rust programming style that dodges these, perhaps at the cost of some optimizations. Using the first example, for example (The article suggests this): Don't return an `&str`; use those for transient things only like function parameters; not for struct fields or returned types.

I'm starting to wonder what I'm missing out by doing this. Not addressed in the article: Any tips for using the more abstract features, like Cow etc? I hit a problem with this today, where a lib used Cow<&str> instead of String, and the lifetime errors bubbled up into my code.

edit: I found this amusing about the article: They demo `String` as a param, and `&str` as a return type for triggering errors; you can dodge these errors simply by doing the opposite!

replies(3): >>43987394 #>>43987527 #>>43987752 #
2. ansc ◴[] No.43987394[source]
+1, would be super interesting to learn when this case makes sense! I am doing great with just using owned in structs for single, and (A)Rc for multiple, but it would be cool to learn.
3. vlmutolo ◴[] No.43987527[source]
You can definitely get around a lot of the pain points by using owned types like String as much as possible instead of borrowed types like &str. This is even generally recommended; there’s often no benefit to using the more advanced features of the language.

Usually the advanced features come in when you’re looking for better performance. It helps performance a lot to use reference types (borrowed types) to eliminate deep copies (and allocations) with .clone() in a loop, for example.

Library authors usually don’t have the luxury of knowing how their code will be used downstream, so diligent authors try to make the code reasonably performant and use these advanced language features to do so. You never know if the consumer of your library will use your function in a hot loop.

4. steveklabnik ◴[] No.43987752[source]
> I'm starting to wonder what I'm missing out by doing this.

It depends. In some cases, you aren't missing anything. In others, you may lose a bit of efficiency by doing some otherwise un-needed copying. Depending on what you're doing that may be irrelevant.

> Any tips for using the more abstract features, like Cow etc? I hit a problem with this today, where a lib used Cow<&str> instead of String, and the lifetime errors bubbled up into my code.

You can do the same thing as you do with &str by calling into_owned on the Cow, you'd get a String back.