Coming from Rust
| for x in &v | for x in v (borrows) |
| for x in v (moves v) | for x in v.into_iter() |
| let (mut a, b) = t | let (var a, b) = t |
Coming from Rust
Section titled “Coming from Rust”jihoo looks like Rust and shares many of its ideas, so the places where it differs are easy to miss. This page lists them: read it before writing jihoo if you know Rust, and check here when code that “should work” does not. The Grammar is the exact syntax.
Side by side
Section titled “Side by side”| Rust | jihoo |
|---|---|
Vec<i64>, HashMap<K, V> |
Vec(i64), Map(K, V) |
fn f<T: Ord>(x: &T) |
fn f(comptime T: Ord, x: T) |
impl<T: Clone> Clone for Box<T> |
impl(T: Clone) Clone for Box(T) |
struct Pair<T> { a: T } |
struct Pair(T: type) { a: T } |
Vec::new(), Shape::Circle(r) |
Vec.new(), Shape.Circle(r) (no ::) |
Vec::<u8>::new() |
Vec(u8).new() |
let mut x = 0; |
var x = 0 (no semicolons needed) |
x: &T |
x: T (borrowing is the default) |
x: &mut T, call f(&mut x) |
inout x: T, call f(&x) |
x: T (moves) |
sink x: T |
&mut self, self |
inout self, sink self; plain self borrows |
-> &T (a part of the first argument) |
-> ref T; -> inout T for &mut T |
|x| x + 1 |
fn(x) { x + 1 } |
impl Fn(i64) -> bool (a parameter) |
fn(i64) -> bool (a borrowed closure), or comptime F: impl fn(i64) -> bool, sink f: F |
-> impl Iterator<Item = i64>, -> impl Fn(i64) -> i64 |
-> impl Iterator, -> impl fn(i64) -> i64: the body’s type, which callers see |
fn(i64) -> i64 (a pointer) |
fnptr(i64) -> i64 |
Box<dyn Shape> |
dyn Shape (owned; the value moves in where one is expected) |
move |x| x + n |
move fn(x) { x + n }: owns its captures, no allocation |
Box<dyn Fn(i64) -> i64> |
dyn fn(i64) -> i64, fn(x) { x + n } where one is expected |
usize, char |
i64 for lengths and indices; u8 for bytes ('a' is a u8) |
0..=n in a for |
0..n + 1 (..= exists only in patterns) |
if let Some(x) = o { ... } |
match o { Some(x) => ..., None => {} } |
while let Some(x) = it.next() |
loop { let Some(x) = it.next() else { break } ... } |
let Some(x) = o else { return } |
the same; x borrows when o is a place |
format!("{} {:>5.2}", a, b) |
fmt.format("{} {:>5.2}", (a, b)) (import std.fmt): the values are a tuple |
println!("{}", x) |
println(x) (one argument, with Show), or fmt.println("{} {}", (a, b)) |
#[derive(Clone, PartialEq, Debug)] |
#[derive(Clone, Eq, Show)]; Show prints like {:?} without quotes around strings |
Self::new() |
Self.new() or Type.new() |
x.len() on &str, &[T] |
x.len: a field on str and slices; v.len() on Vec, String, Map |
unsafe { *p }, p.add(n) |
unsafe { *p }, p + n (in elements) |
std::ptr::null() |
null, where a pointer type is expected |
std::mem::take(&mut x) |
mem.take(&x) (after import std.mem) |
AtomicI64, Arc<Mutex<T>> |
sync.Atomic(i64), sync.Mutex(T), borrowed by the threads (no Arc) |
*m.lock().unwrap() += 1 |
m.lock(fn(n) { n += 1 }): the value is lent to the closure |
UnsafeCell<T> |
a #[interior] struct |
loop { break 5 } |
not possible: break takes no value |
debug_assert!(lo <= hi) at the top, contract crates |
requires lo <= hi, ensures ..., invariant ...: contracts, for the verifier, never run |
What does not exist
Section titled “What does not exist”- No
if let,while let, labeled loops orbreak value. Usematch, orlet pattern = value else { ... }, whose block must not finish (return,break,continue,panic). - No macros.
println,print,panicandassertare functions, andstd.fmtformats several values from a tuple. A literal pattern is checked while compiling, asformat!’s is (but a value no placeholder uses is not an error); one made while the program runs is read then, and a malformed one, or a placeholder without a value, panics instead of failing to compile. - No items inside function bodies: helper functions go at the top level.
- No
mutkeyword (varinstead), no&T/&mut Ttypes, no lifetimes.dyn Traitis always owned: there is no&dyn Trait, and adyn fnormove fncannot change what it captured (noFnMut). implis not a parameter’s type (f: impl Fn(..)): write a type parameter,comptime F: impl fn(A) -> R, andsink f: F. A result-> impl Traitis not opaque: the caller sees the body’s type, and itsItem. Eachmove fnhas its own type, so tworeturns of different closures do not fit oneimplresult; usedyn fnfor those.- No
Copytrait to opt into: a type made only of plain parts copies by itself (Values and ownership). - No overloading of
/,%or the bitwise operators.==/!=calleq,</<=/>/>=callcompare,+ - *calladd/sub/mul, and+=/-=calladd_assign/sub_assign. - No
char: text is UTF-8 bytes, and'가'is an error because it is more than one byte. - No default or named arguments, no variadic functions except
extern fn. - No
#[cfg(test)], test modules,assert_eq!or#[should_panic].jihoo test f.jhruns the#[test]functions off.jhand of the modules it imports outside the standard library, each in a process of its own, since a panic stops the whole process rather than unwinding. Tests sit next to the code they test, private functions included.
Ownership differences
Section titled “Ownership differences”let x = place borrows. let name = person.name does not move or copy
the field: name is a borrow, and person cannot change while name is
used. var name = person.name moves (and fails for a field, see below);
.clone() copies. In Rust the same line would move or copy.
var v = Vec(String).new()v.push("a")let first = v[0] // borrows v[0]v.push("b") // error: `v` is changed here while it is borrowedprintln(first)&x is not a shared borrow. Shared borrowing happens by itself
(f(x) lends x). &x means two things: an argument for an inout
parameter (f(&x)), and, outside calls, a raw pointer *T to a place.
The & is required for inout arguments: it shows the reader that x
may change. A method call x.push(1) passes self without it.
Moving out of a field is an error. Only a whole variable can be moved,
or a part of a new value (pair().1, whose other parts are dropped there).
For a field, an element or anything behind a borrow, use .clone(),
mem.take(&x.f) or mem.replace(&x.f, new):
var t = a.s // error: cannot move a part of `a`let t = mem.replace(&a.s, String.new())+ on a String variable moves it when it can: let b = a + "y"
leaves a moved away. When a is borrowed (a parameter, a field) the
compiler copies its text instead. Write a.as_str() + "y" to keep a.
A value with a Drop impl cannot be taken apart. match f { F { fd } => ... } is an error when F has Drop; read its fields instead.
A method called on a ref T value is that of the T. A call
returning ref T (v.first().unwrap(), map.get(k).unwrap()) gives a
borrow as a value; .clone(), .len() or .to_string() on it call the
T’s methods, as Rust’s auto-deref does, so .clone() gives a T that
no longer borrows v. Only a method the T lacks is looked up on the
borrow itself.
Views are not stored in ordinary data. str, [T], closures, ref T
are views. A struct holding one becomes a view itself: it can be a local
and be returned, but the compiler tracks what it borrows, as it would a
Rust struct with a lifetime parameter, without the annotation
(Borrowing).
Pattern differences
Section titled “Pattern differences”- Range patterns include their end, whichever way they are written:
'0'..'9'and'0'..='9'both match'9'. A range expression (for i in 0..9,s[0..9]) leaves the end out. - A bare name is a variant if the matched type has a payload-less variant of
that name, and a binding otherwise. There is no
Tok::Eqvseqdistinction by case:Eq =>matches the variantEqifTokhas one. - Variants are written alone when the type is known (
Circle(r)), or asShape.Circle(r);Some,None,OkandErralways work alone. A(x) | B(x)bindsxfrom whichever alternative matches, as in Rust; every alternative binds the same names with the same types, and a name isvarin all of them or in none. With a guard,A(x) | B(x) if x > 0tries the guard for each alternative that matches.- A
matcharm’s body may be a statement:Run(c) => c += 1. Arms are separated by newlines or commas. match &xlets the arms change what they bind. A plainmatch xon a part of something (a field, an element) or on a borrow borrows the parts it binds. On a new value (a call’s result), or on a whole variable that owns a value with a destructor, the arms move the parts out: the variable is used up by thematch, on every path, not only in the arms that bind. To keep it on the other paths, decide before thematch:if is_expr(s) { match s { ... } } else { keep(s) }.let (a, b) = pairborrows the parts whenpairis a variable (like everylet x = place); to take a value apart,matchit.- A
matchwhose first arm gives a borrowed part is a view of it, aslet x = placeis:let t = match o { Some(t) => t, None => return }borrows the payload whenois borrowed, andocannot change whiletis used. Every other arm must then give a place too (not a new value), and thematchcannot be moved out of:.clone()in the arms makes it owned. - Patterns see through
refandinoutvalues, as Rust’s default binding modes do:Some(Circle(r))matches anOption(ref Shape). let Some(v) = m.get(k) else { ... }keepsvaref V, which borrows what the call borrowed, the map and the key. Astrkey lent where aStringis borrowed becomes aStringover the same bytes that lives to the end of the block, sovcan be used after the statement.None(or another variant) alone as one arm of aniftakes no type from the other arm:let x: Option(u32) = if c { None } else { y }.
Equality and printing
Section titled “Equality and printing”==needs anEqimpl, even for an enum without payloads or a tuple. Compare such values withmatch, or writeimpl Eq for T.String == strandstr == Stringboth work.print/printlnneedShow: integers, floats,bool,strandStringhave it.Vec,Optionand tuples do not; derive or write aShowimpl. A float prints the shortest text that reads back as it, like Rust’s{:?}:1.0,0.30000000000000004,1e21.
Line breaks matter
Section titled “Line breaks matter”Statements end at a newline. An expression continues onto the next line only
after a binary operator, or before a .:
let total = a + // continues blet s = text .trim() // continues: a line may start with `.`let bad = a + b // error: `+ b` is a new statement(, [ and ? at the start of a line do not apply to the line before, and
return followed by a newline returns nothing.
In the head of if, while, match and for, P { x: 1 } is not a
struct literal; write (P { x: 1 }).
Generics
Section titled “Generics”- Type parameters are ordinary parameters marked
comptime, listed with the others; callers may leave them out when they can be inferred (largest(xs)) or pass them first (fill(u8, 4, 0)). Integer parameters work the same way:comptime N: i64. - Several bounds:
comptime T: Ord + Hash. - Bodies are checked per instance, like C++ templates and Zig, so an error
in a generic function names the instance (
note: in the instance ...). impl(T: Number) Ord for Tgives every number type an impl at once; the marker traits arePlain,Int,Signed,Unsigned,Float,Number.- Inherent impls work on any type, built-in ones too: the standard library
has
impl str { ... }.
Integers
Section titled “Integers”- Integer types never convert by themselves;
asconverts (truncating, extending, saturating for floats).asbinds tighter than every binary operator:c as i64 * 2is(c as i64) * 2. - Overflow traps in debug builds, wraps with
--release.+% -% *%always wrap. Unsigned values cannot be negated: write0 -% x. - Literals take the type the context expects (
let b: u8 = 200), elsei64.intis another name fori64. i128andu128exist, but a literal is at most 64 bits: writeu128::MAXas0 -% (1 as u128)and1 << 100for large values.
A translation
Section titled “A translation”// Rustfn count_words(text: &str) -> HashMap<String, usize> { let mut counts = HashMap::new(); for w in text.split(' ') { if w.is_empty() { continue; } *counts.entry(w.to_string()).or_insert(0) += 1; } counts}// jihoofn count_words(text: str) -> Map(String, i64) { var counts = Map(String, i64).new() for w in text.split(" ") { if w.len == 0 { continue } match counts.get_mut(w) { Some(n) => n += 1 None => { counts.insert(w.to_string(), 1) } } } counts}