Motoko Cheat Sheet
• 2 minutes readI’m making this for my own reference, but I hope it helps you out as well!
Language Features
Variables
// Constant variable
let foo = "";
// Stable constant
stable let foo = "";
// Mutable variable
var foo = "";
// Stable mutable
stable var foo = "";
Conditionals
let foo = if 1 else 2;
let mut foo2: Nat = 0;
if else ;
// Do block - not always practical but worth knowing
let option = ?3;
let foo3 = do ?
Assignment
var foo = ;
foo := ;
Loops
let items = [ , , ];
for(val in items.vals()){
Debug.print(debug_show val);
}
Variants
type Foo = {
#bar;
#baz;
};
type Complex = {
#foo : Foo;
#bar : ?Text;
#baz : [Nat];
};
Imports
// base library
// canister import
// package import
Management Canister
type IC = actor ;
let ic : IC = actor ;
import Principal "mo:base/Principal";
import IC "mo:management-canister";
actor Example
For Vessel dependencies, see Vessel
Data Structures
Array
// init
let arr = ;
Iter
import Iter "mo:base/Iter";
let iter = Iter.make;
let fromArr = Iter.fromArray;
let arr2 = Iter.toArray;
Buffer
import Buffer "mo:base/Buffer";
let arr = ;
let buf = Buffer.;
for
let newArr = buf.toArray;
Trie
TrieMap
HashMap
Vessel
// dfx.json
// package-set.dhall
let upstream =
https://github.com/dfinity/vessel-package-set/releases/download/mo-0.6.21-20220215/package-set.dhall sha256:b46f30e811fe5085741be01e126629c2a55d4c3d6ebf49408fb3b4a98e37589b
let packages = [
{ name = "management-canister"
, repo = "https://github.com/krpeacock/ic-management-canister"
, version = "main"
, dependencies = [ "base" ]
},
]
in upstream # packages
// vessell.dhall
{ dependencies = [ "base", "management-canister" ], compiler = Some "0.6.21" }