Golang basics

Built-in stuff

Go comes with some pretty useful things:

Typing

Golang is statically typed.

// declaring a variable
var x int

// initializing a variable
x = 69

// declaring and initializing a variable at the same time
y := 420 // go will infer the type as int when doing this

Visibility

PascalCase means public, camelCase means private:

func Myfunc(){} // public
func myFunc(){} // private

Structs

Structs are just data containers

// declaring a struct
type Server struct {
    Port int
    Host string
}

// initializing a struct
myServer := Server{Port: 80, Host: "localhost"}

Interfaces and pointers

Go interfaces are not explicitly implemented. They’re implicitly satisfied by structs that have the necessary methods.

type Handler interface {
  ServeHTTP()
}

// The Server struct now implicitly implements the Handler interface:
func (d *Server) ServeHTTP() {}

Error handling

Go uses explicit error handling. Functions can return an error type, which you’re expected to check. Make sure to check the error. Seriously, check the errors.

func divide(a int, b int) (int, error) {
  if b == 0 {
    return 0, errors.New("dude wtf")
  }
  return a / b, nil
}

result, err := divide(10, 0)
if err != nil {
  // Handle error
}

Order of execution

Consts (and kind of enums)

const (
  Red = iota // this means auto-increment
  Green
  Blue
)

Common patterns

You are likely to see this in your journey: