Skip to content

Private Fields

Use private to hide a struct field from outside code.

struct User {
name: string
private password: string
}

Private fields cannot be read or modified directly from outside the implementation context.

let user = User()
user.name = "Martin"
// Error:
user.password = "secret"

Methods inside impl can control access to private fields.

struct User {
name: string
private password: string
}
impl User {
fn setPassword(self: User, password: string) void {
self.password = password
}
fn checkPassword(self: User, password: string) bool {
return self.password == password
}
}

Usage:

let user = User()
user.name = "Martin"
user.setPassword("secret")
println(user.checkPassword("secret"))

Private fields are useful for values that should not be changed freely.

Examples:

  • passwords
  • tokens
  • cached internal values
  • file handles
  • database connections
  • internal state flags

Private fields are marked as private in inspection output and skipped by public conversion output.

struct User {
name: string
private password: string
}

The runtime treats password differently from public fields.

The internal $convout hook converts public fields into a dictionary-like output.

Private fields are skipped.

struct User {
name: string
private password: string
}

Public output includes name, but not password.

Use methods to validate private field updates.

struct Account {
private balance: int
}
impl Account {
fn deposit(self: Account, amount: int) void {
if amount <= 0 {
panic("amount must be positive")
}
self.balance = self.balance + amount
}
fn balance(self: Account) int {
return self.balance
}
}