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.
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;
};
};
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
6. Type Aliases
Allow developers to create custom names for types. For example:
type User = { name: Text; age: Nat };
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.
Top comments (0)