Cheat Sheet

Quick reference for Bear syntax. Click any snippet to copy.

Variables & Constants

Immutable
name := 'Bear'
Mutable
mut count := 0
count += 1
Explicit type
age: int = 25
Constant
const pi = 3.14159

Basic Types

Integers
x: int = 42
y: i64 = 100
z: u8 = 255
Floats
pi: f64 = 3.14
small: f32 = 1.0
Strings
s := 'hello'
name := "world"
Booleans
flag := true
other := false
Arrays
nums := [1, 2, 3]
words := ['a', 'b']
Maps
ages := map[string]int{
    'Alice': 30
}

Functions

Basic
fn add(a int, b int) int {
    return a + b
}
No return
fn greet(name string) {
    println('Hello, ${name}')
}
Multiple returns
fn div(a f64, b f64) (f64, bool) {
    if b == 0 { return 0, false }
    return a / b, true
}
Closures
double := fn (x int) int { x * 2 }

Control Flow

If / else
if x > 0 {
    println('positive')
} else {
    println('negative')
}
If expression
status := if age >= 18 { 'adult' } else { 'minor' }
For range
for i in 0 .. 5 {
    println(i)
}
For each
for val in array {
    println(val)
}
Match
match val {
    0 { println('zero') }
    1 { println('one') }
    else { println('other') }
}
Defer
defer { file.close() }

Error Handling

Option
fn find(id int) ?string {
    if id == 1 { return 'Alice' }
    return none
}
Result
fn parse(s string) !int {
    return error('invalid')
}
Or block
val := find(1) or {
    println('not found')
    return
}
Default value
val := risky() or { 0 }

Structs & Methods

Struct
struct Point {
    x f64
    y f64
}
Mutable fields
struct User {
    name string
mut:
    active bool
}
Method
fn (p Point) distance() f64 {
    return (p.x * p.x + p.y * p.y).sqrt()
}
Mutable method
fn (mut u User) activate() {
    u.active = true
}

Concurrency

Goroutine
go worker(id)
Channel
ch := chan int{cap: 10}
ch <- 42
val := <-ch
Producer/consumer
fn produce(ch chan int) {
    for i in 0 .. 5 { ch <- i }
    close(ch)
}
Select
select {
    case msg := <-ch1 { ... }
    case msg := <-ch2 { ... }
}
Mutex
lock counter {
    counter.val++
}

Imports & Modules

Import
import os
import net.http
import json
Named import
import mylib { Function }
C interop
fn C.printf(charptr, ...int) int
Flags
#flag -lmylib
fn C.my_func(int) int