Language basics
Short reference: variables, print, if, loops, and functions.
let and let mut
let is immutable. Use let mut to change the value.
fn main() {
let name = "Sam"
let mut score = 0
score = score + 10
print(score)
}fn main() -> void {
let name: string = "Sam"
let mut score: i32 = 0
score = score + 10
print(score)
}Output
10
print writes to the terminal with a newline after each call.
fn main() {
print("Hello, Nyra!")
print(42)
}fn main() -> void {
print("Hello, Nyra!")
print(42)
}Output
Hello, Nyra!
42
if
Branch execution on a boolean condition.
fn main() {
let n = 7
if n > 5 {
print("big")
} else {
print("small")
}
}fn main() -> void {
let n: i32 = 7
if n > 5 {
print("big")
} else {
print("small")
}
}Output
big
for and while
for over a numeric range; while while the condition is true.
fn main() {
for i in 0..3 {
print(i)
}
let mut n = 0
while n < 2 {
print(n)
n = n + 1
}
}fn main() -> void {
for i in 0..3 {
print(i)
}
let mut n: i32 = 0
while n < 2 {
print(n)
n = n + 1
}
}Output
0
1
2
0
1
fn
Define a function with parameters and call it from main.
fn add(a, b) {
return a + b
}
fn main() {
print(add(2, 3))
}fn add(a: i32, b: i32) -> i32 {
return a + b
}
fn main() -> void {
print(add(2, 3))
}Output
5