我读了 these关于结构的文档,但我不了解单元结构。它说:
Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty enums they can be instantiated, making them isomorphic to the unit type
()
. Unit structs are useful when you need to implement a trait on something, but don’t need to store any data inside it.
他们只以这段代码为例:
struct Unit;
使用单元结构的真实示例是什么?
最佳答案
标准库Global
全局内存分配器, Global
, 是一个单元结构:
pub struct Global;
它没有自己的状态(因为状态是全局的),但它实现了像 Allocator
这样的特性。 .std::fmt::Error
字符串格式错误, std::fmt::Error
, 是一个单元结构:pub struct Error;
它没有自己的状态,但它实现了像 Error
这样的特性。 .RangeFull
..
的类型运算符(operator), RangeFull
, 是一个单元结构:pub struct RangeFull;
它没有自己的状态,但它实现了像 RangeBounds
这样的特性。 .crate
chrono::Utc
Utc
时区是一个单元结构:pub struct Utc;
它没有自己的状态,但它实现了像 TimeZone
这样的特性。因此可用作 Date
的通用参数和 DateTime
.
关于struct - 使用单元结构的真实示例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67689613/