Passing arguments
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
- Rust
- TypeScript
- Python
- bash
Motoko differentiates between immutable arrays, which cannot be altered, and mutable arrays, which can be modified.
import Nat "mo:base/Nat";
actor {
let numbers1 : [Nat] = [1, 2, 3, 4, 5, 6, 7]; // Immutable array
let numbers2 : [var Nat] = [var 1, 2, 3, 4, 5, 6, 7] ; // Mutable array
public func get_numbers(numbers2: [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.
Rust uses the vec
type to represent vectors (sequences, lists, arrays).
let numbers = vec![1, 2, 3, 4, 5, 6, 7 ];
#[query]
fn get_numbers(numbers: Vec<u32>) -> Vec<u32> {
numbers
}
Azle refers to the Vec
type to represent the equivalent of an array
in TypeScript. This is because Vec
aligns with the Candid type.
import { IDL, query } from 'azle';
export default class {
@query([], IDL.Vec(IDL.Nat8))
get_numbers(): Nat {
return [1, 2, 3, 4, 5, 6, 7];
}
}
To learn more about variants in Typescript via Azle, refer to the Azle code.
from kybra import int32, query, Vec
@query
def get_numbers() -> Vec[int32]:
return [1, 2, 3, 4, 5, 6, 7]
To learn more about variants in Python in Kybra, refer to the Kybra book reference on variants.
You can pass a variant as an argument by explicitly specifying the canister name and method name using the dfx
tool in the following format:
dfx canister call canister_name method_name '(variant {})'
Assuming you have a method named get_text
that accepts a Variant
parameter, as exemplified in other examples:
dfx canister call canister_name get_text '(variant {Sun})'
To learn more about calling a method from a canister in bash, refer to the dfx
reference on the dfx canister call command.
For additional examples, refer to type variant in the Candid Reference