Examples
Explore practical Zolo language examples. Click any example to open in the interactive playground.
25 examples 7 categories
let name = "Zolo"
let version = 1
print("Hello, {name} v{version}!")
print("A linguagem moderna com VM em Rust") // output
Hello, Zolo v1! A linguagem moderna com VM em Rust
// let: imutável, const: constante, mut: mutável
let name: str = "Zolo"
const PI: float = 3.14159
let mut counter = 0
counter = counter + 1
counter = counter + 1
print("Nome: {name}")
print("PI: {PI}")
print("Contador: {counter}")
... // output
Nome: Zolo PI: 3.14159
// O pipe |> passa o resultado como primeiro argumento
fn double(x: int) -> int { x * 2 }
fn add_ten(x: int) -> int { x + 10 }
fn square(x: int) -> int { x * x }
let result = 5
|> double()
|> add_ten()
|> square()
print(result) // ((5*2)+10)^2 = 400
... // output
400 Hello, World
fn classify(n: int) -> str {
match n {
0 => "zero",
1..=9 => "single digit",
10..=99 => "double digit",
_ => "large",
}
}
fn day_name(d: int) -> str {
match d {
1 => "Segunda",
... // output
zero single digit
// Iteradores lazy — só calculam o que é necessário
// Quadrados pares dos primeiros 5 números
let result = 0..
|> Iter.map(|x| x * x)
|> Iter.filter(|x| x % 2 == 0)
|> Iter.take(5)
|> Iter.collect()
print(result)
// Fibonacci via Iter.from_fn
... // output
[0, 4, 16, 36, 64] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
struct Point {
x: float,
y: float,
}
impl Point {
fn new(x: float, y: float) -> Point {
return Point { x, y }
}
fn distance(self, other: Point) -> float {
let dx = self.x - other.x
... // output
A: (0.0, 0.0) B: (3.0, 4.0)
enum Shape {
Circle(float),
Rect(float, float),
Triangle(float, float, float),
}
fn area(shape: Shape) -> float {
match shape {
Shape.Circle(r) => 3.14159 * r * r,
Shape.Rect(w, h) => w * h,
Shape.Triangle(a, b, c) => {
let s = (a + b + c) / 2.0
... // output
Círculo com raio 5.0: área = 78.53975 Retângulo 4.0x6.0: área = 24.0
struct Address {
street: str,
city: str?,
}
struct User {
name: str,
address: Address?,
}
let user = User {
name: "Alice",
... // output
Alice: São Paulo Guest: Desconhecida
// @memoize: cache automático de resultados
@memoize
fn fibonacci(n: int) -> int {
if n <= 1 { return n }
return fibonacci(n - 1) + fibonacci(n - 2)
}
// @test: testes inline
@test
fn test_fibonacci() {
assert_eq(fibonacci(0), 0)
assert_eq(fibonacci(1), 1)
... // output
fib(30) = 832040 fib(35) = 9227465
// Closures capturam variáveis do escopo externo
fn make_counter(start: int) {
let mut count = start
return || {
count = count + 1
return count
}
}
let counter = make_counter(0)
print(counter()) // 1
print(counter()) // 2
... // output
1 2
let nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
// Operações básicas
print("Length: {Array.len(nums)}")
print("First: {nums[0]}")
print("Last: {nums[Array.len(nums) - 1]}")
// Funcionais
let evens = nums |> Array.filter(|x| x % 2 == 0)
let doubled = nums |> Array.map(|x| x * 2)
let sum = nums |> Array.reduce(|acc, x| acc + x, 0)
... // output
Length: 10 First: 3
// Generators com fn* e yield
fn* range(start: int, end: int, step: int) {
let mut i = start
while i < end {
yield i
i = i + step
}
}
fn* fibonacci() {
let mut a = 0
let mut b = 1
... // output
0 3
// for com range exclusivo e inclusivo
print("Range 0..5:")
for i in 0..5 {
print(i)
}
print("Range 1..=3:")
for i in 1..=3 {
print(i)
}
// for sobre array
... // output
Range 0..5: 0
fn divide(a: int, b: int) -> Result<int, str> {
if b == 0 {
return Result.Err("divisão por zero")
}
return Result.Ok(a / b)
}
// Verificando e extraindo
let r1 = divide(10, 2)
let r2 = divide(5, 0)
print(r1.is_ok()) // true
... // output
true true
trait Displayable {
fn display(self) -> str
// Implementação padrão
fn debug(self) -> str {
return "[debug] {self.display()}"
}
}
struct Circle {
radius: float,
}
... // output
Círculo(r=5.0) [debug] Círculo(r=5.0)
// Tuplas — destructuring direto no let
fn min_max(nums: [int]) -> (int, int) {
let mut lo = nums[0]
let mut hi = nums[0]
for n in nums {
if n < lo { lo = n }
if n > hi { hi = n }
}
return (lo, hi)
}
let (min, max) = min_max([3, 1, 4, 1, 5, 9, 2, 6])
... // output
Min: 1, Max: 9 17 / 5 = 3 resto 2
// Criação de map
let scores: {str: int} = {
"Alice": 95,
"Bob": 87,
"Carol": 92,
}
// Acesso
print("Alice: {scores["Alice"]}")
print("Bob: {scores.Bob}")
// Iterar sobre entries
... // output
Alice: 95 Bob: 87
// Métodos de string
let s = " Hello, World! "
print(s.trim())
print(s.upper())
print(s.lower())
print(s.trim().len())
// Busca e verificação
let texto = "Zolo is fast and safe"
print(texto.contains("fast"))
print(texto.starts_with("Zolo"))
print(texto.ends_with("safe"))
... // output
Hello, World! HELLO, WORLD!
// Interpolação básica
let name = "Zolo"
let version = 1
print("Linguagem: {name} v{version}")
// Expressões dentro de {}
let price = 9.99
let qty = 3
print("Total: R$ {price * qty:.2f}")
// Floats
let pi = 3.14159265
... // output
Linguagem: Zolo v1 Total: R$ 29.97
// Guards com if nas cláusulas match
fn classify(n: int) -> str {
match n {
n if n < 0 => "negativo",
0 => "zero",
n if n % 2 == 0 && n < 100 => "par pequeno",
n if n % 2 != 0 && n < 100 => "ímpar pequeno",
n if n >= 100 => "grande ({n})",
_ => "desconhecido",
}
}
... // output
-5 => negativo 0 => zero
// Tap operator &. — efeito colateral sem quebrar a chain
let result = [5, 2, 8, 1, 9, 3]
&. print() // imprime o array original
|> Array.filter(|x| x > 3)
&. print() // imprime após filtrar
|> Array.map(|x| x * x)
&. print() // imprime após mapear
|> Array.sort()
print("Final: {result:?}")
// Spread em arrays
... // output
[5, 2, 8, 1, 9, 3] [5, 8, 9]
// if retorna um valor — pode ser usado em qualquer expressão
let score = 85
let grade = if score >= 90 { "A" }
else if score >= 80 { "B" }
else if score >= 70 { "C" }
else { "F" }
print("Nota: {grade}")
// Inline em interpolação
let temp = 38.5
... // output
Nota: B Temperatura 38.5°C: febre
// Funções que recebem e retornam funções
fn compose(f: fn(int) -> int, g: fn(int) -> int) -> fn(int) -> int {
return |x| f(g(x))
}
fn memoize(f: fn(int) -> int) -> fn(int) -> int {
let cache: {int: int} = {}
return |n| {
if let hit = cache[n] { return hit }
let result = f(n)
cache[n] = result
return result
... // output
11 25
// HTTP Server with pipe-based router
fn handle_root(_req) {
return "Hello from Zolo!"
}
fn handle_json(_req) {
return #{"message": "Hello", "language": "Zolo"}
}
fn handle_user(req) {
let id = req.params.id
return #{"id": id, "name": "User {id}"}
... // output
Listening on http://0.0.0.0:3000 [GET] /
use std::Database
use std::SQL
// SQL transpilation for different drivers
let pg = SQL.compile("SELECT * FROM users LIMIT 10", "postgres")
print("Postgres: {pg}")
let ms = SQL.compile("SELECT * FROM users LIMIT 10", "mssql")
print("MSSQL: {ms}")
// SQLite in-memory database
let db = Database.open("sqlite://:memory:")
... // output
Postgres: SELECT * FROM users LIMIT 10 MSSQL: SELECT TOP 10 * FROM users
Want to learn step by step?
The interactive Tutorial guides you through the language with practical exercises and immediate feedback.
Start the Tutorial →