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 to | In Tern |
|---|---|
| classes and methods | a struct plus functions that take it first; p.area() calls area(p) |
None, nil, null, Option | Option[T]: Some(x) or None; test with if o is Some(x): |
exceptions, error, Result | return a Result[T, E] (Ok(v) / Err(e)); r? passes an Err up |
| iterators, comprehensions, streams | xs.map(...), xs.filter(...), xs.sort_by(...), and loops |
| references, pointers, borrowing | values, plus mut parameters and & at the call site |
threads, goroutines, async, Promise.all | parallel: blocks and parallel for |
generics, templates, any | fn 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)ada 50A 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 nstruct 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)cake costs 450
no soup
qty 3
error: not a positive number: -1
error: not a positive number: lotsComprehensions 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)["PEAR", "BANANA", "KIWI"] ["fig", "pear", "kiwi", "banana"] 17Python'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)5133 6057String 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")price 3.14, item #007, 1,234,567 soldWhat 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 likes[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(forstrip),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.0is an error: convert withfloat(1). - Assignment copies.
b = athenb.push(4)leavesaunchanged. In Python both names would see the change. There is nocopy.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
mutand you pass&xs. The&at the call site tells the reader which arguments may change. True/False/Nonearetrue/false/(nothing). There is norange(): write0..n./on ints is integer division (Python's//). There is no**: usemath.pow.- Negative indexes like
xs[-1]compile but fail at run time: writexs[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:
fn main():
names = ["ada", "bob"]
names.append("cy")
print(names)3: error: unknown function `append`
3: hint: arrays grow with `xs.push(value)`Returning None:
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"))5: error: `None` makes an Option, but int is expected hereSay 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))Some(0) -1Writing a class:
class Point:
x: int
y: int
fn main():
print("hi")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:
fn main():
price = 3.5
print(f"{price:.2f}")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:
fn main():
xs = [1, 2, 3]
ys = [x * 2 for x in xs]
print(ys)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:
fn main():
n = 3
print("n = " + n)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:
fn add_tag(tags: [str], t: str):
tags.push(t)
fn main():
tags = ["new"]
add_tag(tags, "sale")
print(tags)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)home 2Go'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)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)499500for 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.serveis 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.
&xexists only as an argument to amutparameter. 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]andb = ashare 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 checkk in m. - Goroutines are tasks:
h = task.spawn(fn() work(x)), thenh.join()(import task); channels arech: chan[int] = task.channel(8).errgroupistask.try_all(fs)(the firstErrcancels the rest) and itsSetLimitistask.try_all_limit(fs, n); aWaitGroupover plain results istask.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++isx += 1,&&isand,:=is=.
Common mistakes
Declaring with :=:
fn main():
n := 5
print(n)2: error: expected a name, found '='
2: hint: variables are created with `=`: `x = 5`Starting a goroutine:
fn main():
xs = [1, 2]
go print(xs)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)3 trueAdding to a shared total from a parallel loop (a race Go would compile):
fn main():
total = 0
parallel for i in 0..100:
total += i
print(total)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 loopTwo tasks writing one variable:
fn main():
total = 0
parallel:
total += 1
total += 2
print(total)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:
fn main():
x = 3
if x > 2 && x < 5:
print(x)3: error: expected `:`, found '&&'
3: hint: write `and`fn main():
x = nil
print(x)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)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)6.0
got 42
not a number: xIterator 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)["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)[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 (withoutBox). - Values freed deterministically by reference counting, with no garbage collector.
takeparameters 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 Tin a parameter type becomesmut T;&Tis justT(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
&xargument can't overlap any other argument of the same call. - Copies are implicit and lazy.
b = ais like a cheapclone()that copies only if one side is later changed. There is noclone()to call. - No traits or generics. Builtins like
map,sort_by, andjson.encodework on every type, but your own functions take one concrete type each. ?works as in Rust onOptionandResult(noFromconversion of error types). There's nopanic!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:
fn main():
let x = 5
print(x)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:
fn first(xs: Vec<int>) int:
return xs[0]
fn main():
print(first([1]))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 typeWriting &mut in the parameter type:
fn bump(n: &mut int):
n += 1
fn main():
x = 1
bump(&x)
print(x)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"):
fn bump(n: mut int):
n += 1
fn main():
x = 1
bump(x)
print(x)6: error: argument 1 of `bump` is `mut`: write `&x` so the change is visible hereClosures written with |x|:
fn main():
xs = [1, 2, 3]
ys = xs.map(|x| x * 2)
print(ys)3: error: unexpected '|'
3: hint: lambdas are written `fn(x) x + 1` (one expression)Iterator adapters:
fn main():
xs = [1, 2, 3]
ys = xs.iter().map(fn(x: int) x * 2).collect()
print(ys)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 collectPassing the same value twice (the borrow checker's "cannot borrow as mutable more than once"):
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)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())}")ada: $7.75reduce 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))["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)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" toostruct 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)ada ADAPromise.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)9 16Template 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
mapandfilterwith short lambdas:x => x * 2isfn(x) x * 2.- Functions as values, closures, and callbacks stored in struct fields.
- JSON everywhere:
json.encodeandjson.decodework 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
intorfloat, and they don't mix:1 + 2.0is 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
nullorundefined. 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; aparallelblock runs tasks on multiple cores and waits for all of them. - Generics use square brackets:
fn first[T](xs: [T]) Tinstead offunction first<T>(xs: T[]): T. - Double-quoted strings only.
len(xs)instead ofxs.length.
Common mistakes
const and let:
fn main():
const name = "ada"
print(name)2: error: `const` goes at the top level of a file; inside a function, write `x = 5`.length:
fn main():
xs = [1, 2, 3]
print(xs.length)3: error: [int] has no field `length`
3: hint: use `len(x)`Single-quoted strings:
fn main():
name = 'ada'
print(name)2: error: unexpected character "'"
2: hint: strings use double quotes: "text" (or `text`, raw, when it holds double quotes)Arrow functions:
fn main():
xs = [1, 2, 3]
ys = xs.map(x => x * 2)
print(ys)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:
fn main():
console.log("hi")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:
fn main():
x = 7
label = x > 5 ? "big" : "small"
print(label)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]})true falseLeaving out a field, as you might with an object literal:
struct User:
name: str
age: int
fn main():
u = User(name="ada")
print(u)6: error: missing field `age` in UserNext 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.