Idioms

Before we start learning basic concepts, let's take a look at some idioms in Spawn. Idioms are common patterns or expressions that are used in a language.

Filter a list

[1, 2, 3, 4].filter(|el| el % 2 == 1) // keep only odd numbers

Check if array contains element

10 in [1, 2, 3, 4]

Iterate over a range

for i in 0 .. 10 {}

Iterate over an array

for index, element in arr {} // or for element in arr {}

Returning multiple values

fn foo() -> (i32, i32) { return 2, 3 } fn main() { a, b := foo() println(a) println(b) c, _ := foo() // ignore values using `_` }

Error handling

// returns i32 or error fn get() -> !i32 { ... } fn main() { val := get() or { println('Error: ${err}') return } println(val) }

If unwrapping

fn get() -> !i32 { ... } fn main() { if val := get() { println(val) } else { println('Error: ${err}') } }

Option chaining

import os fn main() { default_age := os.ARGS.get(0)?.i32() or { 20 } println(default_age) }

If expression

val := if a == 1 { 100 } else if a == 2 { 200 } else { 300 } // or val := if a == 1 { 100 } else if a == 2 { 200 } else { 300 }

Swap two variables

a, b = b, a

Get CLI parameters

import os fn main() { println(os.ARGS) }

Run function in separate thread

fn main() { h := spawn fn () { println('Hello from thread') }() h.join() }

Now let's move on to the basic concepts of the language.