The Rust book mentions that "it is almost always better to use a struct than a tuple struct." Other than the newtype pattern, are there any other advantages of having unnamed fields? Seems to me like the newtype pattern is the only useful case of having tuple structs.
相关问题
- Share Arc between closures
- Function references: expected bound lifetime param
- Pattern matching on slices
- How can I iteratively call Sha256::digest, passing
- Destructure a vector into variables and give away
相关文章
- How can I convert a f64 to f32 and get the closest
- What is a good way of cleaning up after a unit tes
- How can I unpack (destructure) elements from a vec
- How to import macros in Rust?
- How to get struct field names in Rust? [duplicate]
- Confusion between [T] and &[T]
- How do I initialize an opaque C struct when using
- What's the most idiomatic way to test two Opti
They are very similar to each other.
Given the following definitions
we can construct instances of structs and tuple structs as follows
Assignments work as follows
A tuple struct's fields have implicit names (0, 1, ...). Hence, accessing fields is performed as follows
At least for documentation purposes, it's almost always clearer to assign explicit names to the fields of the struct. That's why in the Rust community I've seen many argue for always using a normal struct.
However, there might be cases where the fields of the struct are inherently "anonymous", one notable case being the "newtype" (tuple struct with one field) where you're only wrapping an inner type.
In that case, naming the inner field does not arguably provide any additional information.
vs
The section on structs on the Rust book has more info on newtypes.