Skip to content

09 · Data Structures

Reusable typed field paths

field User::address.city produces a FieldPath<User, str> without reading an instance. get reads the leaf; set returns an immutable update and shares untouched children. Paths preserve privacy and exact leaf types; computed members and linear storage are rejected.

On this page

field User::address.city produces a FieldPath<User, str> without reading an instance. get reads the leaf; set returns an immutable update and shares untouched children. Paths preserve privacy and exact leaf types; computed members and linear storage are rejected.

Complete example

Reusable typed field paths.

23-typed-field-paths.zolo
Playground
// Item 20: a typed field path can be reused and its getter is a callback.

struct Address { city: str, postal_code: str }
struct User { name: str, address: Address, roles: [str] }

fn city_path() -> FieldPath<User, str> = field User::address.city

fn main() {
    let city = city_path()
    let original = User {
        name: "Ana",
        address: Address { city: "São Paulo", postal_code: "01000-000" },
        roles: ["reader"],
    }
    let moved = city.set(original, "Recife")
    print(city.get(original))
    // expected: São Paulo

    print(city.get(moved))
    // expected: Recife

    print(moved.address.postal_code)
    // expected: 01000-000


    let cities = [original, moved].map(city.get)
    print(cities[0])
    // expected: São Paulo

    print(cities[1])
    // expected: Recife


    // The untouched collection is still shared by the immutable update.

    moved.roles.push("reviewer")
    print(original.roles.len())
    // expected: 2

}

Rules and behavior

Records, maps and updates · Documentation

From a checkout of the repository:

zolo examples/features/06-data-structures/23-typed-field-paths.zolo

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br