Skip to main content

Passing arguments

Beginner
Tutorial

Overview

This document aims to provide examples of passing different argument types to a canister.

Arrays

An array is a collection of items of the same data type.

The following example defines an array of numbers and a function that returns the array.

Motoko differentiates between immutable arrays, which cannot be altered, and mutable arrays, which can be modified.

To declare an immutable array (default):

let a : [Nat] = [0, 1, 2, 3];

To declare a mutable array, the [var _] syntax is used:

let a : [var Nat] = [var 0, 1, 2, 3] ;

To declare a function that returns an array:

public func get_numbers(a: [Nat]) : [Nat] {
return a;
}

The Array Motoko base library provides utility functions on arrays. To learn more about the Array Motoko base library, refer to the Motoko base library reference on Array and the Motoko language quick reference on arrays.

Variants

A variant type represents a value that is from exactly one of the given cases, or tags. Similar to enums, they let you differentiate between different types within the same variable.

The following example defines a Day type representing a day of the week. It utilizes a switch statement to match the input Day with one of its variants, returning the corresponding full name of the day.

type Day = {#sun; #mon; #tue; #wed; #thu; #fri; #sat};

public query func get_text(d : Day) : Text {
switch d {
case (#sun) "Sunday";
case (#mon) "Monday";
case (#tue) "Tuesday";
case (#wed) "Wednesday";
case (#thu) "Thursday";
case (#fri) "Friday";
case (#sat) "Saturday";
};
};

For additional examples, refer to the Type variant reference in Motoko.

To learn more about variants in Motoko, refer to Kai Peacock's blog on using Motoko variants.