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:
persistent 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 a stable variable called - greeting. 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 in- greeting.
- 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 current- greetingvalue, followed by the input text. The method body produces a response by concatenating- "Hello, "with the input- name, followed by an exclamation point.