Skip to main content

Variables and constants

Typed names with explicit initial values.

Declarations

Every declaration specifies whether the name is mutable, its type, and an initializer. Sarlin does not declare uninitialised values.

declarations.sar
var difficulty int32 = 2
const multiplier int32 = 100

func main() {
    local var score int32 = difficulty * multiplier
    local const player_name string = "Bob"

    score = score + 50
    print(player_name + ": " + score)
}
  • var declares a mutable name.
  • const declares a name that cannot be reassigned.
  • Inside a function, declarations begin with local.
  • Outside a function, omit local to declare a global.

Scope and names

Locals belong to their enclosing function or block. Parameters are local names. Globals are available to functions throughout the program, including functions declared earlier in the source.

Global initialization

Global initializers run in declaration order before the first statement inmain. Initializers may call functions and use expressions, collections, constructors, and globals already initialized above them. A global initializer cannot refer directly to a later global.

global_expressions.sar
var starting_score int32 = initial_score()
const doubled_score int64 = starting_score * 2
var heading string = "Starting score: " + doubled_score
var bonus_available bool = doubled_score > 40

func initial_score() int32 {
    return 21
}

func main() {
    print(heading)
    print(bonus_available)
}
Output
Starting score: 42
true

Constants and managed values

A constant collection cannot be changed through its constant name. Managed values are references, however, so another mutable reference to the same value can still change it. See Values and copying.