ยง2023-07-12
This tutorial's sequence includes seven brief topics that each illustrate a different part of the language.
-
Create a module -- Write a small module with functions you can call from another module.
-
Call your code from another module -- Import and use your new module.
-
Return and handle an error -- Add simple error handling.
-
Return a random greeting -- Handle data in slices (Go's dynamically-sized arrays).
-
Return greetings for multiple people -- Store key/value pairs in a map.
-
Add a test -- Use Go's built-in unit testing features to test your code.
-
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
- greetings.go as
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
}
$ 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
- hello.go as
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!