-
Notifications
You must be signed in to change notification settings - Fork 0
Variable and constant declarations
circular17 edited this page Sep 20, 2023
·
4 revisions
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 typefloat
-
let x float = 10; y float = 7
defines x and y with explicit typefloat
even if supplied values areint
-
let x/y/z = 0
defines the three identifiersx
,y
andz
to be equal to0
-
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 tox
-
a[1] := 4
to change the content of the element of index1
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 thechangeName
function onperson
will not be possible
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 theage
variable but not its value -
var year = 1996
defines ayear
asint
and that can be modified -
var hello str = [1, 2, 3]
won't work becausestr
and list type are not compatible
Variables can be modified:
-
age := 10
sets theage
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