Skip to content

Variable and constant declarations

circular17 edited this page Sep 20, 2023 · 4 revisions

Constant declarations

A constant is defined by putting the keyword let followed by the name, type (optional) and value of the constant:

  • let pi = 3.14 has implicit type float
  • let x float = 10; y float = 7 defines x and y with explicit type float even if supplied values are int
  • let x/y/z = 0 defines the three identifiers x, y and z to be equal to 0
  • let a = [1, 2, 3] defines a constant list of integers
  • let person = {| firstName: "John", var lastName: "Doe" |}

A constant cannot be modified. Hence it is then not allowed to:

  • x := 5 to assign a new value to x
  • a[1] := 4 to change the content of the element of index 1

This is true as well for variable members:

  • person.lastName := "Crumpet" will not be possible even though lastName is defined as variable

A constant cannot be passed as a mutable parameter to a function (functions always follow the first parameter).

  • mut person changeName to call the changeName function on person will not be possible

Variable declarations

A variable is defined by putting the keyword var followed by the name, type (optional) and value (optional). At least the type or the value must be specified:

  • var age int defines the age variable but not its value
  • var year = 1996 defines a year as int and that can be modified
  • var hello str = [1, 2, 3] won't work because str and list type are not compatible

Variables can be modified:

  • age := 10 sets the age to 10
  • year += 1 adds one year
  • hello[0] := 5 sets the first value of the array (supposing it was properly defined)

Variables can be passed as mutable to functions:

  • mut year addOne supposing the function addOne increments the parameter
Clone this wiki locally