Golang

Introduction

Hello World

package main
 
import "fmt"
 
func main() {
    fmt.Println("Hello Gophers!")
}
Execution
  1. It declares the main package, which is required for executable programs in Go.
  2. It imports the fmt package, which provides formatting and printing functions.
  3. The main() function is the entry point of the program.
  4. Inside main(), it uses fmt.Println() to print "Hello Gophers!" to the console.

Go CLI Commands

Compile and run code

go run[<filename.go]

Compile

go build [filename.go]

Running compiled file

./filename

Test packages

go test [folder]

Install packages/modules

go install [package]

List installed packages/modules

go list

Update packages/modules

go fix

Format package sources

go fmt

See package documentation

go doc [package]

Add dependencies and install

go get [module]

See Go environment variables

go env

See version

go version

Go Modules

Go projects are called modules. Each module has multiple packages Each package should has a scoped functionality. Packages talk to each other to compose the code. A module needs at least one package, the main. The package main needs a entry function called main.

Create Module

$ go mod init [name]
Tip

By convention, modules names has the follow structure: domain.com/user/module/package.
Example: github.com/spf13/cobra

On this page