DEV Community

Elsuraj
Elsuraj

Posted on

Data types and Values in Motoko

Motoko is a strongly-typed programming language designed for the Internet Computer. It provides a variety of types to help developers write safe and efficient code.
Below is an overview of the types in Motoko:

1. Primitive Types
Int: Represents integers (e.g., 42, -7).

Nat: Represents natural numbers (non-negative integers, e.g., 0, 10).

Float: Represents floating-point numbers (e.g., 3.14, -0.5).

Bool: Represents boolean values (true or false).

Text: Represents strings (e.g., "Hello, Motoko!").

2. Composite Types
Tuples: A fixed-size collection of values of different types (e.g., (42, "hello", true)).

Arrays: A collection of values of the same type (e.g., [1, 2, 3]).

Records: A collection of named fields with associated types (e.g., { name: "Alice"; age: 30 }).

Variants: A type that can hold one of several possible values (e.g., #Ok(42) or #Err("Failed")).

3. Function Types
Functions in Motoko are first-class citizens and have types. For example:


func add(x : Int, y : Int) : Int { x + y };
The type of add is (Int, Int) -> Int.
Enter fullscreen mode Exit fullscreen mode

4. Actor Types
Actors are the building blocks of Motoko programs on the Internet Computer. They encapsulate state and behavior and communicate asynchronously via messages.

Example:

actor Counter {
    var count : Nat = 0;
    public func increment() : async Nat {
        count += 1;
        return count;
    };
};
Enter fullscreen mode Exit fullscreen mode

5. Optional Types
Represent values that may or may not be present. For example:


let maybeValue : ?Int = null; // No value
let someValue : ?Int = ?42;   // Has a value
Enter fullscreen mode Exit fullscreen mode

6. Type Aliases
Allow developers to create custom names for types. For example:

type User = { name: Text; age: Nat };

Enter fullscreen mode Exit fullscreen mode

Motoko's type system is designed to ensure safety and clarity in smart contract development. By leveraging its rich set of types, developers can build robust and maintainable applications on the Internet Computer. Whether you're working with primitive types, actors, or generics, Motoko provides the tools you need to write efficient and secure code.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs