Hello, world!
“Hello, world!” is a common starting point used to showcase a programming language’s basic syntax.
Below is an example of “Hello, world!” written in Motoko:
// If an actor is declared with the persistent keyword, all private declarations are considered stable by defaultpersistent actor HelloWorld { // We store the greeting in a stable variable such that it gets persisted over canister upgrades. var greeting : Text = "Hello, ";
// This update method modifies the greeting prefix. public func setGreeting(prefix : Text) : async () { greeting := prefix; };
// This query method returns the currently persisted greeting with the given name. public query func greet(name : Text) : async Text { return greeting # name # "!"; };};In this example:
-
The code begins by defining an actor named
HelloWorld. In Motoko, an actor is an object capable of maintaining state and communicating with other entities via message passing. -
It then declares the variable
greeting. This is a stable variable because the actor is declared with the keywordpersistent. Stable variables are used to store data that persists across canister upgrades. Read more about canister upgrades. -
An update method named
setGreetingis used to modify the canister’s state. This method specifically updates the value stored ingreeting. -
Finally, a query method named
greetis defined. Query methods are read-only and return information from the canister without changing its state. This method returns the currentgreetingvalue, followed by the input text. The method body produces a response by concatenating"Hello, "with the inputname, followed by an exclamation point.