3 ms·
<3 Rust The only thing I find difficult in Rust is lifetimes of e.g. "String"s in data structures, e.g. in Scala I have: case class CustomerSale(name:Stri
by KingOfCoders 6y ago
<3 Rust
The only thing I find difficult in Rust is lifetimes of e.g. "String"s in data structures, e.g. in Scala I have:
case class CustomerSale(name:String, item:String)
and because of GC I don't have to think about life times, copying etc. - data gets removed after a request or when nothing is used any longer.
In Rust it is
struct CustomerSale{
name: String,
item: String,
}
which rarely works that simple. I need to think of the life times of name and item, e.g. when I get them from a database, and I don't want to own it, or if I want to copy them or have &str etc. And in web frameworks in Rust there is no notion of request life times which would make things much easier.
- pitaj 6y agoIf you use String which is heap allocated, you don't really need to worry about lifetimes. &str on the other hand
- KingOfCoders 6y agoYes, String was an oversimplification, String means I either own or copy it, both things I usually don't want to do, so I end up - as you've said - with &str.
- phaylon 6y agoYou might want to look into using `Arc<str>`. It's an immutable string slice that can have many owners and will be dropped once the last one is done with it.
- KingOfCoders 6y agoThanks, I will try that - fearing my code is littered with Arc ;-) - but sarcasm aside, thanks.
- phaylon 6y agoI usually just have a `type Text = std::sync::Arc<str>` at the root, specifically during prototyping :)
- rmdashrfstar 6y agoHow does this differ from just sharing &str?
- phaylon 6y agoA `&str` is a borrow of the string slice data, and has borrowing semantics. An `std::sync::Arc<str>` on the other hand isn't borrowed but has shared ownership and is atomically reference counted. Does that answer the question? Could you expand on what you mean by sharing `&str`?
- rmdashrfstar 6y agoI suppose my question is what motivates the use of atomically referencing counting string slice rather than borrowing?
- phaylon 6y agoYou can store it independently without it being borrowed. So your structs don't need lifetimes. I consider it a midpoint between `String` and `&str`. Most of the convenience of `String` (barring mutation) but less costly.