ยง2023-07-12

This tutorial's sequence includes seven brief topics that each illustrate a different part of the language.

  1. Create a module -- Write a small module with functions you can call from another module.

  2. Call your code from another module -- Import and use your new module.

  3. Return and handle an error -- Add simple error handling.

  4. Return a random greeting -- Handle data in slices (Go's dynamically-sized arrays).

  5. Return greetings for multiple people -- Store key/value pairs in a map.

  6. Add a test -- Use Go's built-in unit testing features to test your code.

  7. Compile and install the application -- Compile and install your code locally.

$ mkdir greetings && cd $_
$ go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings

$ cat go.mod 
module example.com/greetings

go 1.20
package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    // var message string
    // message = fmt.Sprintf("Hi, %v. Welcome!", name)
    // was shirted as follows,
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}
  1. Call your code from another module
$ mkdir hello && cd $_
$ go mod init 
$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello

$ cat go.mod
module example.com/hello

go 1.20
package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}
$ go mod edit -replace example.com/greetings=../greetings

$ cat go.mod
module example.com/hello

go 1.20

replace example.com/greetings => ../greetings

$ go mod tidy
go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000

$ cat go.mod
module example.com/hello

go 1.20

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0-00010101000000-000000000000

$ go run .
Hi, Gladys. Welcome!