使用单元结构的真实示例是什么?
我阅读了这些关于结构的文档,但我不了解单元结构。它说:
单元结构最常用作标记。它们的大小为零字节,但与空枚举不同,它们可以被实例化,使它们与单元类型同构
()。当您需要在某物上实现特征但不需要在其中存储任何数据时,单元结构很有用。
他们只以这段代码为例:
struct Unit;
使用单元结构的真实示例是什么?
回答
标准库
Global
全局内存分配器Global是一个单元结构:
pub struct Global;
它没有自己的状态(因为状态是全局的),但它实现了像Allocator.
std::fmt::Error
字符串格式的错误std::fmt::Error, 是一个单元结构:
pub struct Error;
它没有自己的状态,但它实现了像Error.
RangeFull
..运算符的类型RangeFull是一个单元结构:
pub struct RangeFull;
它没有自己的状态,但它实现了像RangeBounds.
板条箱
chrono::Utc
的Utc时区是一个单元结构:
pub struct Utc;
It has no state of its own, but it implements traits like TimeZone and is thus usable as a generic argument to Date and DateTime.
- [`Utc`](https://docs.rs/chrono/0.4.19/chrono/offset/struct.Utc.html) timezone from the chrono trait - a unit struct, no state of its own, but implements the `TimeZone` trait and hence usable as generric argument to `Date` and `DateTime`.