Skip to main content

Golang (Go)

Official page

Install Go

  • Operating system Ubuntu
  1. Download package

    curl -OL https://golang.org/dl/go1.22.4.linux-amd64.tar.gz
  2. Extract application

    rm -rf /usr/local/go && tar -C /usr/local -xzf go1.22.4.linux-amd64.tar.gz
  3. Set new path

    • Open file ~/.profile and add the following path to the end of your file
    export PATH=$PATH:/usr/local/go/bin
  4. Reload profile with new path

    source ~/.profile
  5. Verify go version

    go verion

    Output:

    go version go1.22.4 linux/amd64

Go code

After you installed Go programming language, you can try program your first program in Go, Hello, World!.

  1. Prepare directory for your project

    mkdir go-example
    cd go-exmaple
  2. Initial your project

    $ go mod init example/hello
    go: creating new go.mod: module example/hello
  3. Create new file with name hello.go via your code editor and insert the following code

    package main

    import "fmt"

    func main() {
    fmt.Println("Hello, World!")
    }
  4. Execute your code

    $ go run .
    Hello, World!

External packages

Sometimes you will need to implement external functions in your code. You can search https://pkg.go.dev/ for third-party packages with the right features for your project

  1. Import package to your Go code

    package main

    import "fmt"

    import "rsc.io/quote"

    func main() {
    fmt.Println(quote.Go())
    }
  2. Install requirements

    $ go mod tidy
    go: finding module for package rsc.io/quote
    go: downloading rsc.io/quote v1.5.2
  3. Execute your code

    $ go run .
    Don't communicate by sharing memory, share memory by communicating.

Project structure

Very good examples how to structure a project in Go:


Source: