Go comes with some pretty useful things:
gofmt
(no need to prettify using third party tools)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
PascalCase means public, camelCase means private:
func Myfunc(){} // public
func myFunc(){} // private
Structs are just data containers
// declaring a struct
type Server struct {
Port int
Host string
}
// initializing a struct
myServer := Server{Port: 80, Host: "localhost"}
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() {}
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
}
main
is calledinit
, it will be called automagically before main
const
keyword to define constantsconst (
Red = iota // this means auto-increment
Green
Blue
)
You are likely to see this in your journey:
New
functions for creating structssrc
and a cmd
directories to separate entrypoints from lib codegithub.com/company/project
tools.go
file to manage dev dependencies