# Settings for Golang
export GOROOT=/usr/local/go # golang binary distribution
export GOPATH=$HOME/go # packages
export PATH=$GOPATH/bin:$PATH
type keyword.type MyInt int
type MyString string
Generate a random integer from 0 to 99.
Formatting string (fmt):
%v → the value in a default format. when printing structs, the plus flag (%+v) adds field names.%#v → a Go-syntax representation of the value.%q → a single-quoted character literal safely escaped with Go syntax.%T → check variable's type.%U → represent code points (rune type) as Unicode.package main
import "fmt"
type SomeStruct struct {
i int
c rune
s string
}
func main() {
s := SomeStruct{97, 'b', "text"}
fmt.Printf("%v\n%+v\n%#v\n%q\n\n", s, s, s, s)
v := 42
fmt.Printf("v is of type %T\n", v)
}
// output:
/*
%v: {97 98 text}
%+v: {i:97 c:98 s:text}
%#v: main.SomeStruct{i:97, c:98, s:"text"}
%q: {'a' 'b' "text"}
v is of type int
*/
Format a Go string without printing: s := fmt.Sprintf("foo: %s", bar)
fmt.Println() accepts multiple parameters:
fmt.Println("abc", "def", "ghi")
// output:
// abc def ghi
// import "strconv"
a := strconv.Itoa(23)
Compile and install the application (binary executable):
cd to module's directory
Discover the Go install path by $ go list -f '{{.Target}}', truncate the last directory name, remember the path
Add the install directory to system's shell path. $ export PATH=$PATH:/path/to/your/install/directory.
<aside> 💡
As an alternative, we can also change the Go install path rather than modifying shell path.
</aside>
$ go install
Run application by simply typing its name. $ hello
Errors are printed by logger, not Println.
Two-value assignment are executed separately.
Read from keyboard.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your city: ")
city, _ := reader.ReadString('\n')
fmt.Print("You live in " + city)
}
method 1:
$ go build hello.go
$ ./hello
method 2:
$ go run hello.go