Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - What are some use cases for tuple structs?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They are very similar to each other.

Given the following definitions

struct TupleStruct(i32, i32);
struct NormalStruct {
    a: i32,
    b: i32,
}

we can construct instances of structs and tuple structs as follows

let ts = TupleStruct(1, 2);
let ns = NormalStruct { a: 1, b: 2 };

// shortcut to initialize the fields of a struct using the values of the
// fields of another struct
let ns2 = NormalStruct { a: 5, ..ns };
let ts2 = TupleStruct { 0: 1, ..ts }; // for TupleStruct it needs curly brackets
                                      // and implicit field names

Assignments work as follows

let TupleStruct(x, y) = ts;
println!("x: {}, y: {}", x, y);

let NormalStruct { a, b } = ns;
println!("a: {}, b: {}", a, b);

A tuple struct's fields have implicit names (0, 1, ...). Hence, accessing fields is performed as follows

println!("Accessing ns by name - {}{}", ns.a, ns.b);
println!("accessing ts by name - {}{}", ts.0, ts.1);

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.

struct Inches {
    inner: i32,
}

vs

struct Inches(i32);

The section on structs on the Rust book has more info on newtypes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...