Pular para o conteúdo

12 · Orientação a Objetos

Tipos de identidade genéricos

Declare newtype Id<T>(int) para distinguir identificadores como Id<User> e Id<Order>. O argumento de tipo continua fazendo parte da identidade nominal mesmo sem ocupar espaço em runtime. Aliases preservam esses argumentos.

Nesta página

Declare newtype Id<T>(int) para distinguir identificadores como Id<User> e Id<Order>. O argumento de tipo continua fazendo parte da identidade nominal mesmo sem ocupar espaço em runtime. Aliases preservam esses argumentos.

Exemplo completo

Tipos de identidade genéricos.

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())

Referência

Referência · Programa fonte

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

Veja também

Índice global

Encontre seu caminho pela Zolo

Experimente uma ideia

Comece por aqui

9 resultados

9 resultados

enespt-br