09 · Data Structures
Typed record projection
user.{ id, name } evaluates user once and creates a fresh anonymous record with only the selected visible physical fields. Exact types survive projection. Duplicate selections, inaccessible or computed fields and forbidden linear copies are rejected.
On this page
user.{ id, name } evaluates user once and creates a fresh anonymous record with only the selected visible physical fields. Exact types survive projection. Duplicate selections, inaccessible or computed fields and forbidden linear copies are rejected.
Complete example
Typed record projection.
// Typed projection selects visible physical fields into an anonymous record.
struct User { id: int, name: str, internal: str }
var acquired = 0
fn make() -> User { acquired += 1; User { id: acquired, name: "Ada", internal: "hidden" } }
let public_user = make().{ name, id }
print(acquired)
print(public_user.id)
print(public_user.name)
let updated = public_user with { id += 4 }
print(public_user.id)
print(updated.id)
let empty = make().{}
print(acquired)
struct Box<T> { value: T, id: int }
macro selected(value) { $value.{ value } }
let integer_box: Box<int> = Box { value: 7, id: 1 }
let text_box: Box<str> = Box { value: "text", id: 2 }
let integer = selected!(integer_box)
let text = selected!(text_box)
print(integer.value)
print(text.value)
fn first() -> int { let unused = ({ return 8; User { id: 0, name: "", internal: "" } }).{ id }; 0 }
print(first())
var total = 0
:outer for n in 0..3 {
let value = ({ if n == 1 { continue :outer }; User { id: n, name: "", internal: "" } }).{ id }
total += value.id
}
print(total)
Rules and behavior
Records, maps and updates · Documentation
From a checkout of the repository:
zolo examples/features/record-projection.zolo
Projection paths and aliases
value.{ field, nested.field as name } copies selected stored fields into an anonymous record. The base is evaluated once. Each path must be visible and follow the existing copy rules. Computed accessors cannot be projected, and output names must be unique.
// Prepare a public response without copying internal fields.
struct Address { city: str, delivery_code: int }
struct User { id: int, name: str, address: Address }
let user = User {
id: 7,
name: "Ada",
address: Address { city: "Recife", delivery_code: 42 }
}
let response = user.{ id, name as display_name, address.city as city }
print("{response.id}: {response.display_name}, {response.city}")
See also