Saltar al contenido

12 · Programación Orientada a Objetos

Tipos de identidad genéricos

Declara newtype Id<T>(int) para distinguir identificadores como Id<User> e Id<Order>. El argumento de tipo sigue formando parte de la identidad nominal aunque no ocupe espacio en runtime. Los alias conservan esos argumentos.

En esta página

Declara newtype Id<T>(int) para distinguir identificadores como Id<User> e Id<Order>. El argumento de tipo sigue formando parte de la identidad nominal aunque no ocupe espacio en runtime. Los alias conservan esos argumentos.

Ejemplo completo

Tipos de identidad 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())

Referencia

Referencia · Programa fuente

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

Consulta también

Índice global

Encuentra tu camino por Zolo

Prueba una idea

Empieza aquí

9 resultados

9 resultados

enespt-br