Tern

Coming from Python, Go, Rust, or JavaScript

This guide translates what you already know into Tern. There is one section per language. Each shows common code side by side with its Tern version, lists what carries over and what is different, and ends with the mistakes people from that language make most often, with the compiler's actual error message and hint. Read the section for the language you know best; the language reference has the complete rules.

Tern in one paragraph

Tern reads like Python but is statically typed and compiled to native code. Every value is a copy: assigning or passing an array, map, or struct never creates a second name for the same data (copies are lazy, so this is cheap). There are no references, pointers, None/null, classes, exceptions, or generics. A function can change its caller's variable only if its parameter is declared mut and the caller writes & at the call site. Because nothing is shared, the compiler can check parallel code for data races before it runs.

You are used toIn Tern
classes and methodsa struct plus functions that take it first; p.area() calls area(p)
None, nil, null, OptionOption[T]: Some(x) or None; test with if o is Some(x):
exceptions, error, Resultreturn a Result[T, E] (Ok(v) / Err(e)); r? passes an Err up
iterators, comprehensions, streamsxs.map(...), xs.filter(...), xs.sort_by(...), and loops
references, pointers, borrowingvalues, plus mut parameters and & at the call site
threads, goroutines, async, Promise.allparallel: blocks and parallel for
generics, templates, anyfn first[T](xs: [T]) T, struct Pair[A, B], constraints T: Ord
"%.2f", {:.2}, toFixed(2)f"{fmt.fixed(x, 2)}" and the rest of the fmt module

Coming from Python

Side by side

A class becomes a struct plus functions. Where Python would give a field a default, write a constructor function. Method-call syntax still works: acct.deposit(50) calls deposit(&acct, 50) when the first parameter is mut.

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

acct = Account("ada")
acct.deposit(50)
print(acct.owner, acct.balance)
struct Account:
    owner: str
    balance: int

fn new_account(owner: str) Account:
    return Account(owner, 0)

fn deposit(a: mut Account, amount: int):
    a.balance += amount

fn main():
    acct = new_account("ada")
    acct.deposit(50)
    print(acct.owner, acct.balance)
Output
ada 50

A function that returns None when it finds nothing returns a sentinel, or fills a mut parameter and returns whether it found something. An exception becomes a returned status.

def find_price(prices, name):
    return prices.get(name)          # None if missing

def parse_qty(s):
    n = int(s)                       # raises ValueError
    if n <= 0:
        raise ValueError("must be positive")
    return n
struct Qty:
    ok: bool
    value: int
    error: str

fn find_price(prices: {str: int}, name: str, price: mut int) bool:
    if not (name in prices):
        return false
    price = prices[name]
    return true

fn parse_qty(s: str) Qty:
    n = s.trim().to_int(-1)
    if n <= 0:
        return Qty(false, 0, f"not a positive number: {s}")
    return Qty(true, n, "")

fn main():
    prices = {"tea": 300, "cake": 450}
    p = 0
    if find_price(prices, "cake", &p):
        print("cake costs", p)
    if not find_price(prices, "soup", &p):
        print("no soup")
    for s in ["3", "-1", "lots"]:
        q = parse_qty(s)
        if q.ok:
            print("qty", q.value)
        else:
            print("error:", q.error)
Output
cake costs 450
no soup
qty 3
error: not a positive number: -1
error: not a positive number: lots

Comprehensions become map and filter, which take a lambda written fn(x) expression. sorted(key=...) becomes sort_by, which returns a new array (plain sorted(xs) is xs.sorted()). sum takes an array, not a generator: map first.

words = ["pear", "fig", "banana", "kiwi"]
long_upper = [w.upper() for w in words if len(w) > 3]
by_length = sorted(words, key=len)
total = sum(len(w) for w in words)
fn main():
    words = ["pear", "fig", "banana", "kiwi"]
    long_upper = words.filter(fn(w) len(w) > 3).map(fn(w) w.upper())
    by_length = words.sort_by(fn(w) len(w))
    total = sum(words.map(fn(w) len(w)))
    print(long_upper, by_length, total)
Output
["PEAR", "BANANA", "KIWI"] ["fig", "pear", "kiwi", "banana"] 17

Python's multiprocessing or concurrent.futures becomes a parallel block, which runs on real threads with no pickling and no GIL:

from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as ex:
    a, b = ex.map(count_primes, [50_000, 60_000])
fn count_primes(n: int) int:
    count = 0
    for i in 2..n:
        d = 2
        prime = true
        while d * d <= i:
            if i % d == 0:
                prime = false
                break
            d += 1
        if prime:
            count += 1
    return count

fn main():
    parallel:
        a = count_primes(50_000)
        b = count_primes(60_000)
    print(a, b)
Output
5133 6057

String formatting: f-strings work, but without format specs. Use the fmt module for decimals and padding.

import fmt

fn main():
    price = 3.14159
    n = 7
    print(f"price {fmt.fixed(price, 2)}, item #{fmt.zero_pad(n, 3)}, {fmt.thousands(1234567)} sold")
Output
price 3.14, item #007, 1,234,567 sold

What carries over

  • Indentation for blocks, : to open them, # comments, if/elif/else, while, for x in xs:, break, continue, pass.
  • and, or, not, in; f-strings; slices like s[1..], xs[..2] (with .., not :).
  • String methods under slightly different names: split, join (called on the separator, as in Python), replace, find, upper, lower, trim (for strip), starts_with, ends_with.
  • Dicts and lists as built-in {K: V} maps and [T] arrays. Maps keep insertion order.

What's different

  • Types are required on parameters and return values, and a variable's type can't change. 1 + 2.0 is an error: convert with float(1).
  • Assignment copies. b = a then b.push(4) leaves a unchanged. In Python both names would see the change. There is no copy.deepcopy, because you never need it.
  • Parameters are read-only. A Python function can quietly append to the list you pass it; a Tern function can't, unless the parameter is mut and you pass &xs. The & at the call site tells the reader which arguments may change.
  • True/False/None are true/false/(nothing). There is no range(): write 0..n.
  • / on ints is integer division (Python's //). There is no **: use math.pow.
  • Negative indexes like xs[-1] compile but fail at run time: write xs[len(xs) - 1].
  • There are no global variables. Put settings in a struct and pass it, or write a function that returns the constant.
  • Duck typing doesn't exist: a function takes specific types. For code that works on many types, write a generic function: fn first[T](xs: [T]) T.

Common mistakes

Calling Python's list methods:

Does not compile
fn main():
    names = ["ada", "bob"]
    names.append("cy")
    print(names)
Compiler output
3: error: unknown function `append`
3: hint: arrays grow with `xs.push(value)`

Returning None:

Does not compile
fn find_user(names: [str], want: str) int:
    for i, n in names:
        if n == want:
            return i
    return None

fn main():
    print(find_user(["ada"], "ada"))
Compiler output
5: error: `None` makes an Option, but int is expected here

Say that the result may be missing: return an Option[int], and the caller unwraps it.

fn find_user(names: [str], want: str) Option[int]:
    for i, n in names:
        if n == want:
            return Some(i)
    return None

fn main():
    print(find_user(["ada"], "ada"), find_user(["ada"], "bob").unwrap_or(-1))
Output
Some(0) -1

Writing a class:

Does not compile
class Point:
    x: int
    y: int

fn main():
    print("hi")
Compiler output
1: error: expected `fn`, `struct`, `enum`, `type`, `const`, or `extern` at the top level
1: hint: there are no classes: declare data with `struct Name:` (fields only) and write functions that take it first; `p.f()` calls `f(p)`

A format spec in an f-string:

Does not compile
fn main():
    price = 3.5
    print(f"{price:.2f}")
Compiler output
3: error: can't read `price:.2f` inside the f-string
3: hint: f-strings have no format specs: `import fmt`, then `{fmt.fixed(x, 2)}` (2 decimals), `fmt.zero_pad(n, 3)`, `fmt.pad_left(s, width, " ")`

A list comprehension:

Does not compile
fn main():
    xs = [1, 2, 3]
    ys = [x * 2 for x in xs]
    print(ys)
Compiler output
3: error: expected `,`, found 'for'
3: hint: there are no comprehensions: `xs.map(fn(x) ...)` and `xs.filter(fn(x) ...)`, or a loop with `push`

Adding a number to a string:

Does not compile
fn main():
    n = 3
    print("n = " + n)
Compiler output
3: error: `+` with mismatched types str and int (use float()/int() to convert)
3: hint: convert with `str(n)` ("n=" + str(n)) or use an f-string: f"n={n}"

Changing a list that was passed in:

Does not compile
fn add_tag(tags: [str], t: str):
    tags.push(t)

fn main():
    tags = ["new"]
    add_tag(tags, "sale")
    print(tags)
Compiler output
2: error: can't modify parameter `tags`: parameters are read-only unless declared `mut`
2: hint: to change only a local copy, copy it first (`tags2 = tags`) and change `tags2`; to change the caller's value, declare `tags: mut T` and call with `f(&x)` or `x.f()`

The fix is fn add_tag(tags: mut [str], t: str) called as add_tag(&tags, "sale"), or tags.add_tag("sale").

Coming from Go

Side by side

Go is the closest in spirit: structs plus functions, explicit error returns, one binary. Methods on a struct become functions that take it first, and a pointer receiver becomes a mut parameter.

type Counter struct {
    name string
    hits int
}

func (c *Counter) Hit() { c.hits++ }

func main() {
    c := Counter{name: "home"}
    c.Hit()
    c.Hit()
    fmt.Println(c.name, c.hits)
}
struct Counter:
    name: str
    hits: int

fn hit(c: mut Counter):
    c.hits += 1

fn main():
    c = Counter(name="home", hits=0)
    c.hit()
    c.hit()
    print(c.name, c.hits)
Output
home 2

Go's (value, error) and (value, ok) returns become a struct, a mut parameter plus a bool, or an enum. There is no nil: a result is always present.

func lookup(m map[string]int, k string) (int, bool) {
    v, ok := m[k]
    return v, ok
}

func parsePort(s string) (int, error) {
    n, err := strconv.Atoi(s)
    if err != nil || n < 1 || n > 65535 {
        return 0, fmt.Errorf("bad port %q", s)
    }
    return n, nil
}
enum PortResult:
    Port(n: int)
    Bad(msg: str)

fn parse_port(s: str) PortResult:
    n = s.to_int(-1)
    if n < 1 or n > 65535:
        return PortResult.Bad(f"bad port \"{s}\"")
    return PortResult.Port(n)

fn main():
    m = {"a": 1}
    v = m.get("b", 0)                       # Go's zero value when missing
    print(v, "b" in m)                      # and the `ok`
    for s in ["8080", "http"]:
        match parse_port(s):
            Port(n):
                print("listening on", n)
            Bad(msg):
                print("error:", msg)
Output
0 false
listening on 8080
error: bad port "http"

Goroutines with a sync.WaitGroup become a parallel: block, which waits for its tasks at the end. Each task writes its own variable, so there is nothing to lock.

var wg sync.WaitGroup
var left, right int
wg.Add(2)
go func() { defer wg.Done(); left = sum(data[:half]) }()
go func() { defer wg.Done(); right = sum(data[half:]) }()
wg.Wait()
fn sum(xs: [int], lo: int, hi: int) int:
    t = 0
    for i in lo..hi:
        t += xs[i]
    return t

fn main():
    data: [int] = []
    for i in 0..1000:
        data.push(i)
    half = len(data) / 2
    parallel:
        left = sum(data, 0, half)
        right = sum(data, half, len(data))
    print(left + right)
Output
499500

for i := 0; i < n; i++ becomes for i in 0..n:, and for i, x := range xs becomes for i, x in xs:. fmt.Sprintf("%05d %.2f", n, x) becomes f"{fmt.zero_pad(n, 5)} {fmt.fixed(x, 2)}".

What carries over

  • Structs, functions, and composition instead of inheritance. No classes, no exceptions.
  • Explicit error handling by return value, and a small standard library you import by name.
  • One native binary. http.serve is built in, with a thread per core and an event loop.
  • Packages are directories of files that share a namespace, and names are private by a naming rule (Go: lowercase; Tern: a leading _).
  • A data race is a bug, and the tools catch it: Go at run time with -race (sometimes); Tern at compile time (always).

What's different

  • No pointers. &x exists only as an argument to a mut parameter. A struct can't point at another struct; linked data uses indexes into an array.
  • Slices don't share memory. In Go, b := a[1:3] and b = a share the backing array. In Tern, every slice and assignment is a copy (made lazily, so it's cheap).
  • No zero values by default. A struct is built with all its fields, and a missing map key is a runtime error unless you use m.get(k, default) or check k in m.
  • Goroutines are tasks: h = task.spawn(fn() work(x)), then h.join() (import task); channels are ch: chan[int] = task.channel(8). errgroup is task.try_all(fs) (the first Err cancels the rest) and its SetLimit is task.try_all_limit(fs, n); a WaitGroup over plain results is task.all(fs). parallel: blocks are fork-join for computation.
  • No interface. For behavior that varies, pass a function value: fn(int) str.
  • Generics are type parameters, as in Go 1.18+: fn first[T](xs: [T]) T, struct Pair[A, B].
  • x++ is x += 1, && is and, := is =.

Common mistakes

Declaring with :=:

Does not compile
fn main():
    n := 5
    print(n)
Compiler output
2: error: expected a name, found '='
2: hint: variables are created with `=`: `x = 5`

Starting a goroutine:

Does not compile
fn main():
    xs = [1, 2]
    go print(xs)
Compiler output
3: error: expected end of line, found 'print'
3: hint: for concurrency, use a `parallel:` block (each line is a task) or `parallel for i in 0..n:`

Returning two values works as in Go, with a tuple type:

fn divide(a: int, b: int) (int, bool):
    if b == 0:
        return 0, false
    return a / b, true

fn main():
    q, ok = divide(7, 2)
    print(q, ok)
Output
3 true

Adding to a shared total from a parallel loop (a race Go would compile):

Does not compile
fn main():
    total = 0
    parallel for i in 0..100:
        total += i
    print(total)
Compiler output
4: error: iterations of `parallel for` run at the same time, so writing `total` from every iteration would race; store per-iteration results in an array indexed by `i`, or combine results after the loop

Two tasks writing one variable:

Does not compile
fn main():
    total = 0
    parallel:
        total += 1
        total += 2
    print(total)
Compiler output
5: error: data race on `total`: the task on line 4 writes it while the task on line 5 writes it at the same time. Give each task its own variable and combine them after the block

&& and nil:

Does not compile
fn main():
    x = 3
    if x > 2 && x < 5:
        print(x)
Compiler output
3: error: expected `:`, found '&&'
3: hint: write `and`
Does not compile
fn main():
    x = nil
    print(x)
Compiler output
2: error: unknown variable `nil`
2: hint: there is no nil: a value that may be missing is an Option (`Some(x)` or `None`)

Coming from Rust

Side by side

A struct with an impl block becomes a struct plus functions. &mut self becomes a mut parameter, and &self a plain one. There are no lifetimes because nothing is borrowed: read-only parameters are passed without copying, and the compiler proves it's safe.

struct Stack { items: Vec<i64> }

impl Stack {
    fn push(&mut self, x: i64) { self.items.push(x); }
    fn peek(&self) -> Option<i64> { self.items.last().copied() }
}
struct Stack:
    items: [int]

fn push(s: mut Stack, x: int):
    s.items.push(x)                        # the builtin push: s.items is an array

fn peek(s: Stack, out: mut int) bool:
    if len(s.items) == 0:
        return false
    out = s.items[len(s.items) - 1]
    return true

fn main():
    s = Stack([])
    s.push(4)
    s.push(9)
    top = 0
    if s.peek(&top):
        print("top", top)
Output
top 9

(push is also a builtin; a call picks yours when its first argument is a Stack. See builtin names.)

Option[T] and Result[T, E] are built in (Some, None, Ok, Err), and ? returns early as in Rust. if let Some(v) = x is written if x is Some(v):. match works as in Rust: it must cover every variant, and it binds payloads by position.

enum Shape { Circle(f64), Rect(f64, f64) }

fn area(s: &Shape) -> f64 {
    match s {
        Shape::Circle(r) => std::f64::consts::PI * r * r,
        Shape::Rect(w, h) => w * h,
    }
}

fn parse(s: &str) -> Result<i64, String> {
    s.parse::<i64>().map_err(|_| format!("not a number: {s}"))
}
import math

enum Shape:
    Circle(r: float)
    Rect(w: float, h: float)

enum Parsed:
    Good(v: int)
    Bad(msg: str)

fn area(s: Shape) float:
    match s:
        Circle(r):
            return math.pi() * r * r
        Rect(w, h):
            return w * h

fn parse(s: str) Parsed:
    v = s.to_int(0)
    if v == 0 and s != "0":
        return Parsed.Bad(f"not a number: {s}")
    return Parsed.Good(v)

fn main():
    print(area(Shape.Rect(2.0, 3.0)))
    for s in ["42", "x"]:
        match parse(s):
            Good(v):
                print("got", v)
            Bad(msg):
                print(msg)
Output
6.0
got 42
not a number: x

Iterator chains become map, filter, and sort_by on arrays. They return new arrays right away; there is no lazy iterator and no collect().

let names: Vec<String> = users.iter()
    .filter(|u| u.active)
    .map(|u| u.name.to_uppercase())
    .collect();
struct User:
    name: str
    active: bool

fn main():
    users = [User("ada", true), User("bob", false), User("cy", true)]
    names = users.filter(fn(u) u.active).map(fn(u) u.name.upper())
    print(names)
Output
["ADA", "CY"]

Rayon's par_iter becomes parallel for, and rayon::join becomes parallel:. The race check is the same idea as Rust's Send/Sync rules, applied to plain variables: iteration i may write out[i], and nothing else shared.

let out: Vec<i64> = xs.par_iter().map(|x| x * x).collect();
fn main():
    xs = [1, 2, 3, 4, 5]
    out = [0] * len(xs)
    parallel for i in 0..len(xs):
        out[i] = xs[i] * xs[i]
    print(out)
Output
[1, 4, 9, 16, 25]

format!("{:>8.2}", x) becomes fmt.pad_left(fmt.fixed(x, 2), 8, " ").

What carries over

  • The safety guarantees you rely on: no null, no dangling references, no use after move, no data races, no aliased mutation. Tern checks them at compile time too.
  • Enums with payloads, exhaustive match, and recursive enums (without Box).
  • Values freed deterministically by reference counting, with no garbage collector.
  • take parameters are Rust's move: the caller can't use the value afterwards.
  • Performance in the same range for most code (see the benchmarks in the README).

What's different

  • No references or lifetimes. &mut T in a parameter type becomes mut T; &T is just T (read-only, and passed without a copy). You write & only at the call site.
  • Mutation is exclusive per call, not per scope. The rule is simply that a &x argument can't overlap any other argument of the same call.
  • Copies are implicit and lazy. b = a is like a cheap clone() that copies only if one side is later changed. There is no clone() to call.
  • No traits or generics. Builtins like map, sort_by, and json.encode work on every type, but your own functions take one concrete type each.
  • ? works as in Rust on Option and Result (no From conversion of error types). There's no panic! to call: runtime errors (an index out of range, a missing map key, unwrap() on None) end the program, or answer 500 inside a web handler, and can't be caught.
  • One integer type (int, 64-bit, wrapping) and one float type (float, 64-bit).

Common mistakes

let bindings:

Does not compile
fn main():
    let x = 5
    print(x)
Compiler output
2: error: expected end of line, found 'x'
2: hint: variables are created by assigning: `x = 5` (no let/var/const)

Generic types in signatures:

Does not compile
fn first(xs: Vec<int>) int:
    return xs[0]

fn main():
    print(first([1]))
Compiler output
1: error: expected `,`, found '<'
1: hint: array types are `[int]`, map types `{str: int}`, tuple types `(int, str)`, and a generic type's arguments go in `[ ]` (`Pair[int, str]`, `Option[int]`); there is no set type

Writing &mut in the parameter type:

Does not compile
fn bump(n: &mut int):
    n += 1

fn main():
    x = 1
    bump(&x)
    print(x)
Compiler output
1: error: expected a name, found '&'
1: hint: parameters are written `name: type`, e.g. `fn f(a: int, b: str)`

Forgetting the & at the call site (Rust would say "expected &mut"):

Does not compile
fn bump(n: mut int):
    n += 1

fn main():
    x = 1
    bump(x)
    print(x)
Compiler output
6: error: argument 1 of `bump` is `mut`: write `&x` so the change is visible here

Closures written with |x|:

Does not compile
fn main():
    xs = [1, 2, 3]
    ys = xs.map(|x| x * 2)
    print(ys)
Compiler output
3: error: unexpected '|'
3: hint: lambdas are written `fn(x) x + 1` (one expression)

Iterator adapters:

Does not compile
fn main():
    xs = [1, 2, 3]
    ys = xs.iter().map(fn(x: int) x * 2).collect()
    print(ys)
Compiler output
3: error: unknown function `iter`
3: hint: loop directly: `for x in xs:` (or `for i, x in xs:`)
3: error: unknown function `collect`
3: hint: `split`, `map`, and `filter` already return arrays; there are no iterators to collect

Passing the same value twice (the borrow checker's "cannot borrow as mutable more than once"):

Does not compile
struct Account:
    balance: int

fn transfer(a: mut Account, b: mut Account, n: int):
    a.balance -= n
    b.balance += n

fn main():
    acct = Account(10)
    transfer(&acct, &acct, 5)
    print(acct)
Compiler output
10: error: `transfer` would see the same value twice: `&acct` can be changed, but `acct` is also passed (argument 2)

Coming from JavaScript

Side by side

Objects and classes become structs, which are declared once with typed fields. Every field must be given when building one.

class Cart {
  constructor(owner) { this.owner = owner; this.items = []; }
  add(name, cents) { this.items.push({ name, cents }); }
  total() { return this.items.reduce((t, i) => t + i.cents, 0); }
}
const cart = new Cart("ada");
cart.add("tea", 350);
console.log(`${cart.owner}: $${(cart.total() / 100).toFixed(2)}`);
import fmt

struct Item:
    name: str
    cents: int

struct Cart:
    owner: str
    items: [Item]

fn add(c: mut Cart, name: str, cents: int):
    c.items.push(Item(name, cents))

fn total(c: Cart) int:
    t = 0
    for i in c.items:
        t += i.cents
    return t

fn main():
    cart = Cart("ada", [])
    cart.add("tea", 350)
    cart.add("cake", 425)
    print(f"{cart.owner}: ${fmt.cents(cart.total())}")
Output
ada: $7.75

reduce has no builtin: it is a loop. map, filter, and a sort with a key work much as in JavaScript, except that sort_by returns a new array and takes a key function instead of a comparator.

const adults = people.filter(p => p.age >= 18).map(p => p.name);
const byAge = [...people].sort((a, b) => a.age - b.age);
struct Person:
    name: str
    age: int

fn main():
    people = [Person("ada", 36), Person("kid", 9), Person("bob", 25)]
    adults = people.filter(fn(p) p.age >= 18).map(fn(p) p.name)
    by_age = people.sort_by(fn(p) p.age)
    print(adults, by_age.map(fn(p) p.name))
Output
["ada", "bob"] ["kid", "bob", "ada"]

null and undefined become an enum (or a sentinel), and try/catch becomes a returned status. JSON.parse becomes json.decode, which fills a typed value and returns false on bad input instead of throwing.

let settings;
try {
  settings = JSON.parse(text);
} catch (e) {
  settings = { theme: "light", fontSize: 14 };
}
import json

struct Settings:
    theme: str
    font_size: int

fn main():
    settings = Settings("light", 14)
    if not json.decode(`{"theme": "dark"}`, &settings):
        print("bad settings, using defaults")
    print(settings)
    other = Settings("light", 14)
    print(json.decode("{oops", &other), other)
Output
Settings{theme: "dark", font_size: 14}
false Settings{theme: "light", font_size: 14}

Objects are shared by reference in JavaScript; Tern values are not. Here the JavaScript function changes the caller's object, and the Tern one can't unless it asks for mut:

function rename(user) { user.name = user.name.toUpperCase(); return user; }
const a = { name: "ada" };
const b = rename(a);        // a.name is now "ADA" too
struct User:
    name: str

fn renamed(u: User) User:
    v = u                                   # a copy
    v.name = v.name.upper()
    return v

fn main():
    a = User("ada")
    b = renamed(a)
    print(a.name, b.name)
Output
ada ADA

Promise.all over CPU work becomes a parallel: block. Unlike async, the tasks really run at the same time on different cores (JavaScript would need Web Workers):

const [a, b] = await Promise.all([slowSquare(3), slowSquare(4)]);
fn slow_square(n: int) int:
    t = 0
    for i in 0..n:
        t += n
    return t

fn main():
    parallel:
        a = slow_square(3)
        b = slow_square(4)
    print(a, b)
Output
9 16

Template literals become f-strings: `${a} + ${b}` is f"{a} + {b}". toFixed(2) is fmt.fixed(x, 2), and padStart(5, "0") is fmt.pad_left(s, 5, "0").

What carries over

  • map and filter with short lambdas: x => x * 2 is fn(x) x * 2.
  • Functions as values, closures, and callbacks stored in struct fields.
  • JSON everywhere: json.encode and json.decode work on any struct, array, or map.
  • A web server in a few lines, with a handler that takes a request and returns a response.
  • === semantics for == on numbers, strings, and bools: no coercion, ever.

What's different

  • Static types. Every parameter has a type, and a variable keeps its type. Numbers are either int or float, and they don't mix: 1 + 2.0 is an error.
  • Values, not references. Assigning an object or array copies it, and == on structs or arrays is an error rather than a reference comparison.
  • No null or undefined. Every variable starts with a value, and every struct field must be given when the struct is built.
  • No event loop or async. Code runs top to bottom; a parallel block runs tasks on multiple cores and waits for all of them.
  • Generics use square brackets: fn first[T](xs: [T]) T instead of function first<T>(xs: T[]): T.
  • Double-quoted strings only. len(xs) instead of xs.length.

Common mistakes

const and let:

Does not compile
fn main():
    const name = "ada"
    print(name)
Compiler output
2: error: `const` goes at the top level of a file; inside a function, write `x = 5`

.length:

Does not compile
fn main():
    xs = [1, 2, 3]
    print(xs.length)
Compiler output
3: error: [int] has no field `length`
3: hint: use `len(x)`

Single-quoted strings:

Does not compile
fn main():
    name = 'ada'
    print(name)
Compiler output
2: error: unexpected character "'"
2: hint: strings use double quotes: "text" (or `text`, raw, when it holds double quotes)

Arrow functions:

Does not compile
fn main():
    xs = [1, 2, 3]
    ys = xs.map(x => x * 2)
    print(ys)
Compiler output
3: error: unexpected '>'
3: hint: match arms are `Pattern:` followed by an indented block (or `Pattern: stmt` on one line); lambdas are `fn(x) x + 1`

console.log:

Does not compile
fn main():
    console.log("hi")
Compiler output
2: error: unknown variable `console`
2: hint: use `print(...)`
2: error: unknown function `log`
2: hint: use `print(...)` (`math.log` is the logarithm)

The ternary operator:

Does not compile
fn main():
    x = 7
    label = x > 5 ? "big" : "small"
    print(label)
Compiler output
3: error: expected end of line, found 'big'
3: hint: there is no `c ? a : b`; write `a if c else b`

Comparing arrays with == compares their elements (JavaScript's === would compare identities; Tern has none):

fn main():
    a = [1, 2]
    b = [1, 2]
    print(a == b, {"k": a} == {"k": [1, 3]})
Output
true false

Leaving out a field, as you might with an object literal:

Does not compile
struct User:
    name: str
    age: int

fn main():
    u = User(name="ada")
    print(u)
Compiler output
6: error: missing field `age` in User

Next steps

  • The tour walks through the language in order.
  • Values, mut, and & explains the part that is new to everyone.
  • The cookbook has short programs for everyday tasks.
Source: docs/guides/coming-from.md. Every example on this page is compiled and run by tern x test docs.