元组结构有哪些用例? [英] What are some use cases for tuple structs?

查看:42
本文介绍了元组结构有哪些用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 书中提到使用结构体几乎总是比使用元组结构体更好."除了 newtype 模式,具有未命名字段还有其他优点吗?在我看来,newtype 模式是拥有元组结构的唯一有用情况.

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.

推荐答案

它们彼此非常相似.

鉴于以下定义

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

分配工作如下

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

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

元组结构的字段具有隐式名称(0、1、...).因此,访问字段执行如下

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);

至少出于文档目的,为结构体的字段分配显式名称几乎总是更清晰.这就是为什么在 Rust 社区中我看到很多人争论总是使用普通结构.

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.

但是,在某些情况下,结构体的字段本身可能是匿名的",一个值得注意的情况是newtype"(具有一个字段的元组结构体),其中您只包装了一个内部类型.

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,
}

对比

struct Inches(i32);

Rust 书中关于结构的部分 有更多关于新类型的信息.

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

这篇关于元组结构有哪些用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆