What is a real world example of using a unit struct?

Viewed 1908

I read these docs about structs, but I don't understand about unit structs. It says:

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.

they only give this piece of code as an example:

struct Unit;

What is a real world example of using a unit struct?

1 Answers

Standard library

Global

The global memory allocator, Global, is a unit struct:

pub struct Global;

It has no state of its own (because the state is global), but it implements traits like Allocator.

std::fmt::Error

The error for string formatting, std::fmt::Error, is a unit struct:

pub struct Error;

It has no state of its own, but it implements traits like Error.

RangeFull

The type for the .. operator, RangeFull, is a unit struct:

pub struct RangeFull;

It has no state of its own, but it implements traits like RangeBounds.

Crates

chrono::Utc

The Utc timezone is a unit struct:

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.

Related