Programming

Go programming language

Go - tutorial day 1

Installation, follow your OS instructions.

In Fedora, can’t be simpler:

# dnf install golang

GOPATH, Go Workspace and Code Organization

Go requires an specific way to organize the code.

By convention, all your code and the imported code should live in a single workspace. The workspace is just a directory structure on your filesystem pointed by GOPATH environment variable.

In our examples:

  go
  ├── bin
  ├── pkg
  └── src

Where:

  $ echo $GOPATH
  /home/gomix/go

Hello World

Subdirectory

$ cd go
$ mkdir src/hola
/home/gomix/go
├── bin
├── pkg
└── src
    └── hola

Source code

src/hola/hola.go

package main

import "fmt"

func main() {
	fmt.Println("Hola Go Gomix@Fedora, 世界")
}

Running you app

~(gomix) go run hola                                                                                      
Hola Go Gomix@Fedora, 世界 

Building the binary

go run compiles and execute but do not produces a binary. To produce a binary use go build:

~(gomix) go build hola                                                                                    
~(gomix) ls                                                                                               
bin  hola  pkg  src                                                                     
~(gomix) ./hola                                                                                           
Hola Go Gomix@Fedora, 世界  

Building and installation in bin

Simillar to go build but result gets installed in bin.

$ go install hola
.
├── bin
│   └── hola
├── pkg
└── src
    └── hola
        └── hola.go