Skip to content

12 · Object-Oriented Programming

Generic identity types

Declare newtype Id<T>(int) to distinguish identifiers such as Id<User> and Id<Order>. The type argument remains part of nominal identity even when it has no runtime storage. Aliases preserve those arguments.

On this page

Declare newtype Id<T>(int) to distinguish identifiers such as Id<User> and Id<Order>. The type argument remains part of nominal identity even when it has no runtime storage. Aliases preserve those arguments.

Complete example

Generic identity types.

11-generic-newtypes.zolo
Playground
// A user id and an order id can use the same storage without sharing a type.

struct User {}
struct Order {}
newtype Id<T>(int) deriving Eq, Clone
type UserId = Id<User>
type OrderId = Id<Order>

fn user_label(id: UserId) -> str = "user_{id.unwrap()}"

let user = UserId.new(42)
let order = OrderId.new(42)
let make_user_id = UserId.new

print(user_label(user))
print(user_label(make_user_id(7)))
print(user.clone() == user)
print(order.unwrap())

Reference

Reference · Source program

zolo run examples/features/40-syntax-fourth/11-generic-newtypes.zolo --no-cache

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br