Golang basics
Built-in stuff
Go comes with some pretty useful things:
- Source code formatting with
gofmt(no need to prettify using third party tools) - JSON serializadion and deserialization
- Http client/server
- Testing framework
- Generic interface for SQL drivers
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 thisVisibility
PascalCase means public, camelCase means private:
func Myfunc(){} // public
func myFunc(){} // privateStructs
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
- The function
mainis called - If there is a function called
init, it will be called automagically beforemain
Consts (and kind of enums)
- One can use the
constkeyword to define constants - Consts can't be user-defined types
- A set of constants is often used as an ENUM
const (
Red = iota // this means auto-increment
Green
Blue
)Common patterns
You are likely to see this in your journey:
Newfunctions for creating structs- name variables with a single character when convenient
- a
srcand acmddirectories to separate entrypoints from lib code - VCS as project name prefix:
github.com/company/project tools.gofile to manage dev dependencies