Go notes

This post is moved and updated from another project

Golang

Go CLI

go build - compile go run - compile and execute, e.g. go run main.go go fmt - formats all the code in each file in current folder go install - install a package go get - download raw source code from a package go test - yes test

go env - prints out go environment

Source code and files

I have a working folder /helloworld, under that, there is a go source code file called main.go, after compile go build, I can see an executable file called helloworld, run $./helloworld then we can see the results.

Package

In go, package == project == workspace == 1 app

There are two types of packages, one is executable package, which has a file can run; another one is reusable, which is a helper or library.

The package called main is the only executable package! The others are all just libs. go build other package would not get an executable file out.

Go packages

Module

New concept brought in go version 1.11? [need to explain what is module]

go mod init myproject/m - init a module called myproject/m, and created a mod file under current folder

Basic syntax

e.g var card string = "Ace of Spades" equals card := "Ace of Spades"

var new a variable, card is the name of variable, string is the type. := save energy to specify the type when declaring. While the first one can be moved to outside of func, the latter one is invalid outside of function. (interesting)

e.g.

  var hey string
	hey = "sdf"

This is valid in golang, like c, java, kotlin.

Basic Types

bool - is the set of boolean values, true and false; true and false are the two untyped boolean values.

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32
     // represents a Unicode code point

float32 float64

complex64 complex128 // complex128 is the set of all complex numbers with float64 real and imaginary parts

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.