struct - 使用单元结构的真实示例是什么?

标签 struct rust

我读了 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/

相关文章:

rust - 如何在 Rust 中使用按位运算检查文件是否可执行?

syntax - 如何初始化一个结构字段,它是对选项的可变引用?

rust - 为什么 return 语句后面的分号是可选的?

c - 如何匹配结构体数组中的变量,然后是位置

c++ - siginfo 匿名 union 体

即使不需要,编译器也会应用结构填充

c - C 是否将结构填充初始化为零?

c - 对齐结构数组以制作表格

static - 在 Rust 中运行时使用环境变量填充静态/常量

string - 如何从 Rust 中的另一个字符串中删除单个尾随字符串?