### Example Host Output Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/wasm/component-model-tutorial.md The expected output when running the example host with the adder component, demonstrating the addition of two numbers. ```text 5 + 3 = 8 ``` -------------------------------- ### Corrected Example: Providing All Required Fields Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4044.html This example demonstrates the correct way to initialize a struct by providing values for all its required fields. ```moonbit pub(all) struct S { a : Int b : Int } pub let s : S = { a: 1, b: 2 } ``` -------------------------------- ### Test Component with Example Host Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/wasm/component-model-tutorial.md Clone the example host repository, copy your component, and run the host with your component's path and arguments. ```console $ git clone https://github.com/bytecodealliance/component-docs.git $ cd component-docs/component-model/examples/example-host $ cp /path/to/adder.component.wasm . $ cargo run --release -- 5 3 adder.component.wasm ``` -------------------------------- ### Testing Component with Example Host Source: https://docs.moonbitlang.com/en/latest/toolchain/wasm/component-model-tutorial.html Clone the example host repository, copy your component, and run it with cargo. Ensure the component path is correct. ```bash $ git clone https://github.com/bytecodealliance/component-docs.git $ cd component-docs/component-model/examples/example-host $ cp /path/to/adder.component.wasm . $ cargo run --release -- 5 3 adder.component.wasm ``` -------------------------------- ### Snapshot File Content Example Source: https://docs.moonbitlang.com/en/latest/_downloads/78d8998d78e60fd7b1b2f4c9bb2819fb/summary.md This is an example of the content that would be generated by the `record anything` snapshot test. ```text Hello, world! And hello, MoonBit! ``` -------------------------------- ### Install MoonBit Toolchain on Windows Source: https://docs.moonbitlang.com/en/latest/tutorial/tour.html Use this PowerShell command to install the MoonBit toolchain on Windows. It sets the execution policy and then runs the installation script. ```powershell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser; irm https://cli.moonbitlang.com/install/powershell.ps1 | iex ``` -------------------------------- ### Install MoonBit Toolchain on Linux/macOS Source: https://docs.moonbitlang.com/en/latest/tutorial/tour.html Use this command to install the MoonBit toolchain on Linux and macOS systems. It downloads and executes an installation script. ```shell curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash ``` -------------------------------- ### Install wasm-tools Source: https://docs.moonbitlang.com/en/latest/toolchain/wasm/component-model-tutorial.html Install `wasm-tools` for working with WebAssembly components. ```bash $ cargo install wasm-tools ``` -------------------------------- ### Corrected Example: Using Labelled Argument Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4086.html This example shows the correct way to call the function by supplying the required labelled argument. ```moonbit ///| pub fn f(name~ : String) -> Unit { println("Hello, {name}") } ///| test { f(name="John") } ``` -------------------------------- ### Snapshot File Content Example Source: https://docs.moonbitlang.com/en/latest/_sources/language/tests.md This is an example of the content that might be generated in a snapshot file when using `@test.T::write` and `@test.T::writeln`. ```text hello world ``` -------------------------------- ### JavaScript Host Runtime Example for Imported String Constants Source: https://docs.moonbitlang.com/en/latest/toolchain/moon/package.html Example JavaScript code demonstrating how to instantiate a Wasm module with custom imported string constants. ```javascript const { instance } = await WebAssembly.instantiate(bytes, {}, { importedStringConstants: "strings" }); ``` -------------------------------- ### Install wit-bindgen CLI Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/wasm/component-model-tutorial.md Install the wit-bindgen CLI tool, essential for generating MoonBit bindings from WIT files. This tool is crucial for bridging WIT definitions with MoonBit code. ```bash $ cargo install wit-bindgen-cli ``` -------------------------------- ### Corrected Example: Matching Regex at Start and Binding Suffix Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E4184.md This snippet shows the suggested correction for E4184, where the regex is matched at the start of the input, and the suffix is bound only when required. ```moonbit "abc" _ ``` -------------------------------- ### Corrected Map Pattern Match with 'get' Method Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4118.html This example shows the correct implementation of the 'get' method for the 'MyMap' struct, enabling successful map pattern matching. ```moonbit ///| priv struct MyMap { entries : Map[String, Int] } ///| fn MyMap::get(self : MyMap, key : String) -> Int? { self.entries.get(key) } ///| test { let map : MyMap = { entries: { "a": 1, "b": 2, "c": 3 } } match map { { "a": a, .. } => println("a: {a}") _ => println("missing") } } ``` -------------------------------- ### Example moon.pkg with Build Variables Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/module.md Illustrates how build variables outputted by a pre-build script can be used in the `moon.pkg` configuration for native linking. ```text { "link": { "native": { "cc": "${build.CC}" } } } ``` -------------------------------- ### MoonBit Loop Ambiguity Example Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0017.md This erroneous example demonstrates the ambiguous usage of an identifier within a loop, where it refers to the original value before the loop started, leading to unexpected behavior. ```moonbit ///| fn main { var a = 1 loop { println(a) a = a + 1 } } ``` -------------------------------- ### Example moon.pkg using build variables Source: https://docs.moonbitlang.com/en/latest/toolchain/moon/module.html Demonstrates how to use build variables emitted from a pre-build script within the `moon.pkg` configuration, specifically for native linking options. ```moon options( link: { "native": { "cc": "${build.CC}", }, }, ) ``` -------------------------------- ### Corrected MoonBit Code with 'get' Method Implementation Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E4118.md This example shows the corrected MoonBit code where the custom type 'MyType' now implements the 'get' method, resolving the E4118 error and enabling proper map pattern matching. ```moonbit type MyType = { name: string } impl MyType { fn get(self, key: string): option { match key { case "name" => Some(self.name) _ => None } } } let main() = { let data = MyType{name: "test"} match data { case {"name": name} => println(name) _ => println("no match") } } ``` -------------------------------- ### Corrected Enum/Struct Definition in MoonBit Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E3800.md This example demonstrates the correct way to define MoonBit enums and structs using newlines for separation, adhering to the MoonBit style guide and resolving the E3800 error. ```moonbit type MyEnum = | A | B | C struct MyStruct { field1: Int, field2: String, } ``` -------------------------------- ### Create Project Directory and WIT Directory Source: https://docs.moonbitlang.com/en/latest/toolchain/wasm/component-model-tutorial.html Initializes the project directory and creates a subdirectory for WIT definitions. ```bash $ mkdir moonbit-adder && cd moonbit-adder $ mkdir wit ``` -------------------------------- ### Corrected Lexmatch without Leading Rest Binder Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4184.html This corrected example demonstrates the proper way to use lexmatch with the longest strategy. It matches the regex at the start of the remaining input and binds only the suffix when necessary. ```moonbit ///| pub fn match_text(text : String) -> Unit { lexmatch text with longest { ("abc", _) => () _ => () } } ``` -------------------------------- ### Erroneous MoonBit Code for Map Pattern Mismatch Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E4118.md This example demonstrates the MoonBit code that triggers the E4118 error due to an incorrect map pattern usage on a custom type lacking a 'get' method. ```moonbit type MyType = { name: string } let main() = { let data = MyType{name: "test"} match data { case {"name": name} => println(name) _ => println("no match") } } ``` -------------------------------- ### Common MoonBit Development Workflow Source: https://docs.moonbitlang.com/en/latest/_downloads/e5ac02240ae2e8b3e2abd4e3a580c2aa/summary.md This demonstrates the typical command-line sequence to build the frontend and run the backend server. After executing these commands, the application can be accessed via a web browser. ```bash make build-frontend make run-backend ``` -------------------------------- ### Program for Step 1: Finding the Next Redex Source: https://docs.moonbitlang.com/en/latest/example/gmachine/gmachine-1.html Demonstrates the starting point of program execution from the 'main' function and the initial expression to be handled. ```moonbit (defn square[x] (mul x x)) (defn main[] (add 33 (square 3))) ``` -------------------------------- ### Corrected Lexmatch Pattern using Regex Match Expression Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4185.html This example demonstrates the suggested approach using a regex match expression with optional start and end rest binders. This is generally clearer for new code. ```moonbit ///| n fn classify(input : String) -> String { if input =~ (re"a" + re"b", before~, after~) { before.to_owned() + after.to_owned() } else { "none" } } ///| test { inspect(classify("xabz"), content="xz") } ``` -------------------------------- ### Corrected Example: Using 'type' Keyword Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4187.html This example demonstrates the correct way to import a type by prefixing the imported name with the 'type' keyword. This resolves the E4187 compiler error. ```moonbit using @builtin {type Array} fn length(values : Array[Int]) -> Int { values.length() } test { inspect(length([1, 2]), content="2") } ``` -------------------------------- ### Corrected init/main function signature Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E3003.md This example demonstrates the correct signature for `init` and `main` functions, which should have no arguments and no return values. ```moonbit fn init() { } fn main() { } ``` -------------------------------- ### MoonBit Project Structure Example Source: https://docs.moonbitlang.com/en/latest/tutorial/for-go-programmers/index.html Illustrates a typical MoonBit project layout, including source files, configuration files, and package directories. ```text my-project ├── LICENSE ├── README.md ├── moon.mod.json └── src ├── lib │   ├── hello.mbt │   ├── hello_test.mbt │   └── moon.pkg └── main ├── main.mbt └── moon.pkg ``` -------------------------------- ### Install MoonBit Toolchain (Windows) Source: https://docs.moonbitlang.com/en/latest/_downloads/e5ac02240ae2e8b3e2abd4e3a580c2aa/summary.md Installs the MoonBit toolchain on Windows using PowerShell. This command sets the execution policy and then runs the installation script. Restart your terminal or IDE for changes to take effect. ```powershell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser; irm https://cli.moonbitlang.com/install/powershell.ps1 | iex ``` -------------------------------- ### Suggestion: Main package entry point calling library function Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4069.html This example shows the `main.mbt` file for a separate main package that imports and calls a function from the library package. This correctly separates library and entry-point code. ```moonbit ///| fn main { println(@lib.message()) } ``` -------------------------------- ### Create a new MoonBit project and add async dependency Source: https://docs.moonbitlang.com/en/latest/_downloads/e5ac02240ae2e8b3e2abd4e3a580c2aa/summary.md Initializes a new MoonBit project and adds the `moonbitlang/async` library. This is the first step in setting up the CLI project. ```bash moon new download_cli cd download_cli moon add moonbitlang/async@0.19.2 ``` -------------------------------- ### Moon Workspace Manifest Example Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/workspace.md An example of a `moon.work` file, which defines the workspace and its member modules. ```moonbit workspace "my-repo" members { "mod_a" "mod_b" } ``` -------------------------------- ### MoonBit Project Structure Example Source: https://docs.moonbitlang.com/en/latest/_downloads/e5ac02240ae2e8b3e2abd4e3a580c2aa/summary.md Illustrates the directory structure created by `moon new `. It includes main entry points, test files, and configuration files. ```default examine ├── Agents.md ├── cmd │ └── main │ ├── main.mbt │ └── moon.pkg ├── LICENSE ├── moon.mod.json ├── moon.pkg ├── examine_test.mbt ├── examine.mbt ├── README.mbt.md └── README.md -> README.mbt.md ``` -------------------------------- ### Warnings Attribute Example Source: https://docs.moonbitlang.com/en/latest/language/attributes.html Configures warning settings for a top-level declaration. This example disables the 'unused_value' warning. ```moonbit #warnings("-unused_value") fn warnings_example() -> Unit { let x = 42 } ``` -------------------------------- ### Explore the 'buffer' Package Source: https://docs.moonbitlang.com/en/latest/_downloads/7e67a7065021137fc80a2750bac9ee32/summary.md Example of exploring all exported symbols within the '@buffer' package. ```bash $ moon ide doc "@buffer" ``` -------------------------------- ### Create and Run a New MoonBit Project Source: https://docs.moonbitlang.com/en/latest/tutorial/for-go-programmers/index.html Use the 'moon' CLI to create a new project, navigate into its directory, and run it. ```bash $ moon new hello-world $ cd hello-world $ moon run ``` -------------------------------- ### Erroneous Example of Declaration Cycle Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E4155.md This example demonstrates a circular dependency in declarations, which will result in the E4155 error. ```moonbit const a = b const b = a ``` -------------------------------- ### Main entrypoint for the CLI Source: https://docs.moonbitlang.com/en/latest/_sources/tutorial/cli-quickstart.md The `main` function in `cmd/main` handles wiring: reading arguments, building configuration, and calling the library's entrypoint. ```moonbit module main use crate/config use crate/download // start main fn main() { let cfg = config.build_config() async.run(download.run(cfg)) } // end main ``` -------------------------------- ### MoonBit Unused Function Example Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0001.md This is an example of a function that is not used and not marked as public, triggering the `unused_value` warning. ```moonbit fn unused_function() { // This function is not used anywhere } ``` -------------------------------- ### MoonBit init function example Source: https://docs.moonbitlang.com/en/latest/_sources/language/introduction.md The init function is special; it has no parameters or return type, can be called multiple times, and is implicitly executed during package initialization. It should only contain statements. ```moonbit fn init { let x = 1 println(x) } ``` -------------------------------- ### Verify MoonBit Installation Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/wasm/component-model-tutorial.md Check the installed versions of the MoonBit compiler and toolchain. Ensure you have the necessary components for development. ```bash $ moon version --all moon 0.1.20250826 (8ab6c9e 2025-08-26) ~/.moon/bin/moon moonc v0.6.25+d6913262c (2025-08-27) ~/.moon/bin/moonc moonrun 0.1.20250826 (8ab6c9e 2025-08-26) ~/.moon/bin/moonrun moon-pilot 0.0.1-95f12db ~/.moon/bin/moon-pilot ``` -------------------------------- ### Correct Struct Instantiation with Constructor Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4199.html This example demonstrates the correct way to instantiate a struct by defining a constructor function `make_point` and then using it. Alternatively, record construction can be used. ```moonbit ///| pub(all) struct Point { x : Int } ///| fn make_point(x : Int) -> Point { { x, } } ///| test { let point = make_point(1) inspect(point.x, content="1") } ``` -------------------------------- ### Erroneous Partial Match Example Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E0011.html This example demonstrates an incomplete pattern match in MoonBit where the 'None' case is missing. ```moonbit ///| fn main { match Some(1) { // Partial match, some hints: None Some(x) => println(x) } } ``` -------------------------------- ### Initialize GMachine State Source: https://docs.moonbitlang.com/en/latest/example/gmachine/gmachine-2.html Sets up the initial state for the GMachine, including the heap, an empty stack, the initial code to execute (starting with PushGlobal("main") and Eval), global variables, and statistics. ```moonbit let initialState : GState = { heap, stack: @list.empty(), code: @list.from_array([PushGlobal("main"), Eval]), globals, stats: 0, dump: @list.empty(), } ``` -------------------------------- ### Erroneous Example of Unused Field Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0007.md This example demonstrates a struct with a field that is never read, triggering the `unused_field` warning. ```moonbit struct Point { x: Int y: Int } fn main() { let p = Point { x: 1, y: 2 } } ``` -------------------------------- ### Correctly Creating Dynamic Bytes with Buffer Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E4096.md This example shows the recommended way to dynamically create Bytes by using Buffer and explicit UTF-8 writes. ```moonbit fun main() { let name = "world" let buffer = Buffer.new() buffer.write_string("hello ") buffer.write_string(name) let msg = buffer.to_string() printf("%s\n", msg) } ``` -------------------------------- ### Install wasm-tools Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/wasm/component-model-tutorial.md Install wasm-tools for working with WebAssembly components. This utility is part of the WebAssembly toolchain required for component development. ```bash $ cargo install wasm-tools ``` -------------------------------- ### Implement download functionality Source: https://docs.moonbitlang.com/en/latest/_sources/tutorial/cli-quickstart.md The `run` function handles the actual download, streaming the body to stdout or a file based on the output configuration. ```moonbit module download use moonbitlang/core/result use moonbitlang/async as async use moonbitlang/io as io use crate/config // start run fn run(cfg: Config): async[unit] { let res = async.http_client().get(cfg.url) match res { Ok(resp) -> { match cfg.output { "stdout" -> { async.write_all(async.stdout(), resp.body) } "file", path -> { let file = io.open(path, "w") async.write_all(file, resp.body) io.close(file) } } } Err(err) -> { eprintln("Error: {}", err) } } } // end run ``` -------------------------------- ### Erroneous Example: Positional Argument Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4086.html This example demonstrates the error E4086 where a labelled argument is mistakenly treated as a positional argument. ```moonbit ///| pub fn f(name~ : String) -> Unit { println("Hello, {name}") } ///| test { f("John") // Error: The labels name~ are required by this function, but not supplied. } ``` -------------------------------- ### Run Command Example Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/tutorial.md Command to execute a Moonbit program from a specific package. ```bash $ moon run cmd/main 89 ``` -------------------------------- ### Example of a Function for Strictness Analysis Source: https://docs.moonbitlang.com/en/latest/example/gmachine/gmachine-3.html Illustrates the 'abs' function, which will be used as an example to translate into a boolean function for strictness analysis. ```moonbit (defn abs[n] (if (lt n 0) (negate n) n)) ``` -------------------------------- ### View Moon CLI Help Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/tutorial.md Use `moon help` to view the command line usage instructions for the Moon build system. ```bash $ moon help ... ``` -------------------------------- ### Basic Usage of moon ide doc Source: https://docs.moonbitlang.com/en/latest/_downloads/7e67a7065021137fc80a2750bac9ee32/summary.md This shows the fundamental command structure for querying documentation. Replace '' with your search term. ```bash moon ide doc '' ``` -------------------------------- ### MoonBit Unreachable Code Example 1 Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0012.md This example demonstrates unreachable code after a return statement. Ensure all code is reachable. ```moonbit fn main() { let x = 10; if x > 5 { return 1; println!("{}", x); } return 0; } ``` -------------------------------- ### Main entry point for the CLI application Source: https://docs.moonbitlang.com/en/latest/_downloads/e5ac02240ae2e8b3e2abd4e3a580c2aa/summary.md The `main` function in `cmd/main` is the entry point of the CLI. It reads command-line arguments, parses them into a configuration object using the library's `parse_config` function, and then calls the `run` function to execute the download. ```moonbit import { "moonbit-community/cli-quickstart-doc" @app, "moonbitlang/core/env", "moonbitlang/async", } options( "is-main": true, ) async fn main { let argv = @env.args() let config = @app.parse_config(argv[1:]) @app.run(config) } ``` -------------------------------- ### Erroneous Example of Unused Constructor Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0006.md This example shows an enum with a variant that is neither constructed nor read, triggering the E0006 warning. ```moonbit enum Option { Some(Int) None } let x = Option.Some(1) ``` -------------------------------- ### Go Project Initialization Source: https://docs.moonbitlang.com/en/latest/_sources/tutorial/for-go-programmers/index.md Initializes a new Go project and its go.mod file to track dependencies. ```console $ go mod init example.com/my-project ``` -------------------------------- ### Verify Wasm Toolchain Installation Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/wasm/component-model-tutorial.md Confirm the installations of wit-bindgen and wasm-tools by checking their versions. This ensures the tools are correctly set up for use. ```bash $ wit-bindgen --version wit-bindgen-cli 0.45.0 $ wasm-tools --version wasm-tools 1.238.0 ``` -------------------------------- ### Basic Moon Package Configuration Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/package.md Example of a basic `moon.pkg` file. Dependencies are declared in an `import` block. ```moonbit import { use_implement } from "@moonbit/use_implement" ``` -------------------------------- ### Create a new MoonBit project Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/package-manage-tour.md Initialize a new MoonBit project in the specified path using `moon new `. This command generates a starter module with template files. ```shell $ moon new . Created username/myapp at . ``` -------------------------------- ### Corrected struct update example Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E0060.html This example demonstrates how to fix the unused_struct_update warning by either using the updated value or explicitly ignoring it. ```moonbit priv struct User { id : Int name : String email : String } test { let user : User = { id: 0, name: "John Doe", email: "john@doe.com" } let updated = { ..user, email: "john@doe.name" } ignore(updated) } ``` -------------------------------- ### Pattern Matching with Proper Branch Order Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E0012.html This example demonstrates correct pattern matching by ordering branches so that specific cases are handled before general ones, preventing unreachable code. ```moonbit ///| fn example_proper_order() -> Unit { match Some(1) { Some(a) => println("Some(\"{a}\")") _ => println("_") } } ``` -------------------------------- ### Using a Custom Struct Constructor Source: https://docs.moonbitlang.com/en/latest/_downloads/78d8998d78e60fd7b1b2f4c9bb2819fb/summary.md Demonstrates creating an 'IntBox' instance using its custom constructor and inspecting its value. ```moonbit let box = IntBox(10) debug_inspect(box, content="{ value: 10 }") ``` -------------------------------- ### Basic Task Group Example Source: https://docs.moonbitlang.com/en/latest/_sources/language/async-experimental.md Demonstrates the basic usage of `with_task_group` to create multiple tasks that run in parallel. ```moonbit start with_task_group example // Example usage of with_task_group async fn main() { @async.with_task_group(async (group) => { group.spawn_bg(async () => { // Task 1 logic @async.sleep(1000) @console.log("Task 1 finished") }) group.spawn_bg(async () => { // Task 2 logic @async.sleep(500) @console.log("Task 2 finished") }) @console.log("All tasks spawned") }) @console.log("Task group finished") } end with_task_group example ``` -------------------------------- ### Corrected Example with Parentheses Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0051.md This code shows the corrected version of the ambiguous precedence example. Parentheses are added to make the intent clearer. ```moonbit let x = 1 + (2 * 3) ``` -------------------------------- ### Erroneous Example of Unused Trait Bound Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0053.md This example demonstrates code that triggers the E0053 warning because a trait bound is present but not utilized. ```moonbit trait MyTrait { fn foo(self: Self) -> Int } fn bar(x: T) -> Int { // MyTrait::foo is not called return 1 } fn main() { // ... } ``` -------------------------------- ### Importing Packages with Aliases Source: https://docs.moonbitlang.com/en/latest/language/packages.html Demonstrates how to import packages in `moon.pkg` and assign custom aliases for easier access to their entities. ```moonbit import { "moonbit-community/language/packages/pkgA", "moonbit-community/language/packages/pkgC" @c, "moonbitlang/core/builtin", } ``` -------------------------------- ### Example: Using with_task_group for Parallel Tasks Source: https://docs.moonbitlang.com/en/latest/language/async-experimental.html Demonstrates how to use `with_task_group` to spawn multiple background tasks that run concurrently and log their progress. The `with_task_group` ensures all spawned tasks complete before returning. ```moonbit async test "with_task_group" { let log = [] @async.with_task_group(group => { group.spawn_bg(() => { for _ in 0..<3 { log.push("task #1 tick") @async.sleep(200) // sleep for 200ms } }) group.spawn_bg(() => { @async.sleep(100) for _ in 0..<3 { log.push("task #2 tick") @async.sleep(200) } }) }) json_inspect(log, content=[ "task #1 tick", "task #2 tick", "task #1 tick", "task #2 tick", "task #1 tick", "task #2 tick", ]) } ``` -------------------------------- ### Erroneous Example of Unused Catch All Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E0026.md This example demonstrates the deprecated `catch!` syntax which is unnecessary when MoonBit can infer the caught error type. ```moonbit try { // some code } catch! { // handle error } ``` -------------------------------- ### Prelude and Builtin Names Example Source: https://docs.moonbitlang.com/en/latest/_sources/language/packages.md Illustrates how unqualified names are resolved in the current package and the prelude. Local definitions can shadow prelude definitions. ```moonbit let x: Int = 1 let y: String = "hello" let z: Bool = true let w: Unit = () // Prelude and builtin names are available without explicit import. ``` -------------------------------- ### Check if a string starts with a lowercase letter Source: https://docs.moonbitlang.com/en/latest/_downloads/78d8998d78e60fd7b1b2f4c9bb2819fb/summary.md Use the 'is' expression with a character range to check if a string starts with a lowercase letter. ```moonbit fn start_with_lower_letter(s : String) -> Bool { s is ['a'..='z', ..] } ``` -------------------------------- ### Set Heap Start Address for Wasm Backend (JSON) Source: https://docs.moonbitlang.com/en/latest/toolchain/moon/package.html JSON representation of Wasm backend heap start address configuration. ```moon.pkg.json { "link": { "wasm": { "heap-start-address": 1024 } } } ``` -------------------------------- ### MoonBit Main Package Configuration Source: https://docs.moonbitlang.com/en/latest/_sources/tutorial/for-go-programmers/index.md Example configuration for a main package's moon.pkg file in MoonBit, indicating it's a binary package. ```text {literalinclude} /snippets/tutorial/for-go-programmers/src/main/moon.pkg :language: text :caption: src/main/moon.pkg ``` -------------------------------- ### Set Heap Start Address for Wasm Backend Source: https://docs.moonbitlang.com/en/latest/toolchain/moon/package.html Configure the starting address for linear memory that can be used when compiling to the Wasm backend. ```moon.pkg options( link: { "wasm": { "heap-start-address": 1024, }, }, ) ``` -------------------------------- ### Set Heap Start Address for Wasm Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/package.md Specify the starting address of the linear memory available for use when compiling to the Wasm backend. ```moonbit options( link: { "wasm": { "heap-start-address": 1024, }, }, ) ``` -------------------------------- ### Create and Run a New MoonBit Project Source: https://docs.moonbitlang.com/en/latest/_sources/tutorial/for-go-programmers/index.md Use the 'moon new' command to create a new project and 'moon run' to execute it. This is the standard way to start and test MoonBit applications. ```console $ moon new hello-world $ cd hello-world $ moon run ``` -------------------------------- ### Overloading Index Get and Set Operators Source: https://docs.moonbitlang.com/en/latest/_downloads/78d8998d78e60fd7b1b2f4c9bb2819fb/summary.md Implements `_[_]` (get item) and `_[_]=_` (set item) operators for the `Coord` struct using `##alias`. The `get` method takes `Self` and an index, returning an `Int`. The `set` method takes `Self`, an index, and a value, returning `Unit`. ```moonbit struct Coord { mut x : Int mut y : Int } ##alias("_[_]") fn Coord::get(coord : Self, key : String) -> Int { match key { "x" => coord.x "y" => coord.y } } ##alias("_[_]=_") fn Coord::set(coord : Self, key : String, val : Int) -> Unit { match key { "x" => coord.x = val "y" => coord.y = val } } ``` -------------------------------- ### Create New MoonBit Project and Add Dependencies Source: https://docs.moonbitlang.com/en/latest/_downloads/e5ac02240ae2e8b3e2abd4e3a580c2aa/summary.md Initializes a new MoonBit project and adds necessary dependencies for the fullstack application. ```bash moon new fullstack_one_project cd fullstack_one_project moon add moonbitlang/async@0.19.2 moon add moonbit-community/rabbita ``` -------------------------------- ### Go Method Call Example Source: https://docs.moonbitlang.com/en/latest/_sources/tutorial/for-go-programmers/index.md Demonstrates calling methods on a Go struct instance. Note that Scale modifies the struct in place. ```go rect := Rectangle{width: 10.0, height: 5.0} areaValue := rect.Area() rect.Scale(2.0) // NOTE: `.Scale()` modifies the rectangle in place. ``` -------------------------------- ### Erroneous Example: Implicitly Ignored Expression Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E4139.html This example demonstrates the error E4139 where an expression of type `Int` has its value implicitly ignored, which is not allowed. ```moonbit fn main { 1 + 1 // This expression has type Int, its value cannot be implicitly ignored. } ``` -------------------------------- ### Use a Virtual Package in top.mbt Source: https://docs.moonbitlang.com/en/latest/_sources/language/packages.md Demonstrates how to use a virtual package. The `import` field in `moon.pkg` is used to reference the virtual package, and then its entities can be used directly. ```moonbit import virtual-package-name fn main() { virtual_package_name.greet("World") } ``` -------------------------------- ### Erroneous Example of Unused Catch All Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E0026.html This example demonstrates the incorrect usage of the deprecated catch! syntax where the patterns are complete, leading to the E0026 warning. ```moonbit ///| suberror E ///| fn f() -> Unit raise E { raise E } ///| fn g() -> Unit raise { f() catch! { E => raise E } } ///| fn main { g() catch { _ => println("Error") } } ``` -------------------------------- ### Erroneous Example of Unused Try Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E0023.html This example shows a try block that contains code which will not raise an error. The `try` keyword is used unnecessarily. ```moonbit ///| fn main { println("Hello, world!") catch { // `try` is omitted here _ => println("Error") } try { println("Hello, ") println("world!") } catch { _ => println("Error in try block") } } ``` -------------------------------- ### MoonBit main function example Source: https://docs.moonbitlang.com/en/latest/_sources/language/introduction.md The main function serves as the program's entry point and is executed after initialization. It also has no parameters or return type. Only main packages can define a main function. ```moonbit fn main { let x = 2 println(x) } ``` -------------------------------- ### Unused Function Example Source: https://docs.moonbitlang.com/en/latest/language/error_codes/E0001.html This snippet shows an example of an unused function 'greeting' and a local unused function 'local_greeting' within a test block. ```moonbit ///| fn greeting() -> String { "Hello!" } ///| test { fn local_greeting() -> String { "Hello, world!" } } ``` -------------------------------- ### Create a new MoonBit project Source: https://docs.moonbitlang.com/en/latest/_sources/tutorial/fullstack-one-project.md Initializes a new MoonBit project and adds necessary dependencies for async operations and a web framework. ```bash moon new fullstack_one_project cd fullstack_one_project moon add moonbitlang/async@0.19.2 moon add moon-community/rabbita ``` -------------------------------- ### Example Build Script Output (vars) Source: https://docs.moonbitlang.com/en/latest/toolchain/moon/module.html A build script can output variables in the `vars` field, which can then be referenced in `moon.pkg` using `${build.}`. ```json { "vars": { "CC": "gcc" } } ``` -------------------------------- ### Erroneous Example: Missing Toplevel Type Annotation Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E4074.md This example demonstrates the E4074 error where a toplevel declaration is missing a required type annotation. ```moonbit fn main() { let x = 10 let y = "hello" } ``` -------------------------------- ### Test Command Example Source: https://docs.moonbitlang.com/en/latest/_sources/toolchain/moon/tutorial.md Command to run all tests within a Moonbit project. ```bash $ moon test Total tests: 1, passed: 1, failed: 0. ``` -------------------------------- ### Fixed Toplevel Definition Example Source: https://docs.moonbitlang.com/en/latest/_sources/language/error_codes/E4051.md Provides a corrected version of the erroneous toplevel definition example, demonstrating how to resolve E4051 by renaming identifiers. ```moonbit pub val x = 1 pub val y = 2 ```