Go语言 Cheat Sheet
Page content
Rob Pike:
“The key point here is our programmers are Googlers, they’re not researchers. They’re typically, fairly young, fresh out of school, probably learned Java, maybe learned C or C++, probably learned Python. They’re not capable of understanding a brilliant language but we want to use them to build good software. So, the language that we give them has to be easy for them to understand and easy to adopt.”
uinttest with convey
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestStringSliceEqual(t *testing.T) {
Convey("TestStringSliceEqual", t, func() {
Convey("should return true when a != nil && b != nil", func() {
a := []string{"hello", "goconvey"}
b := []string{"hello", "goconvey"}
So(StringSliceEqual(a, b), ShouldBeTrue)
})
Convey("should return true when a == nil && b == nil", func() {
So(StringSliceEqual(nil, nil), ShouldBeTrue)
})
Convey("should return false when a == nil && b != nil", func() {
a := []string(nil)
b := []string{}
So(StringSliceEqual(a, b), ShouldBeFalse)
})
Convey("should return false when a != nil && b != nil", func() {
a := []string{"hello", "world"}
b := []string{"hello", "goconvey"}
So(StringSliceEqual(a, b), ShouldBeFalse)
})
})
}
func TestStringSliceEqualIfBothNotNil(t *testing.T) {
Convey("Given two string slice which are both not nil", t, func() {
a := []string{"hello", "goconvey"}
b := []string{"hello", "goconvey"}
Convey("When the comparision is done", func() {
result := StringSliceEqual(a, b)
Convey("Then the result should be true", func() {
So(result, ShouldBeTrue)
})
})
})
}
build-in types
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32 ~= a character (Unicode code point)
float32 float64
complex64 complex128
range of int type
uint8 : 0 to 255
uint16 : 0 to 65535
uint32 : 0 to 4294967295
uint64 : 0 to 18446744073709551615
int8 : -128 to 127
int16 : -32768 to 32767
int32 : -2147483648 to 2147483647
int64 : -9223372036854775808 to 9223372036854775807
Arrays, Slices
var a [3]int // declare an int array with length 3.
var a = [3]int {1, 2, 3} // declare and initialize a slice
a := [...]int{1, 2} // elipsis -> Compiler figures out array length
a[0] = 1 // set elements
i := a[0] // read elements
var b = a[lo:hi] // creates a slice (view of the array) from index lo to hi-1
var b = a[1:4] // slice from index 1 to 3
var b = a[:3] // missing low index implies 0
var b = a[3:] // missing high index implies len(a)
a = append(a,17,3) // append items to slice a
c := append(a,b...) // concatenate slices a and b
// create a slice with make
a = make([]int, 5, 5) // first arg length, second capacity
a = make([]int, 5) // capacity is optional
// Create a 2-dimensional array
const m, n = 3, 4
var x [m][n]float64
// loop over an array/ slice / struct
for index, element := range a {
}
Shuffle a list
y := make([]T, len(x))
perm := rand.Perm(len(x))
for i, v := range perm {
y[v] = x[i]
}
Atomically read and update variable
var lock sync.RWMutex
lock.Lock()
x = f(x)
lock.Unlock()
Send val via Channel
go func() {
v := <-ch
fmt.Printf("Hello, %v\n", v)
}()
ch <- "Alan"
UDP listen and read
ServerAddr,err := net.ResolveUDPAddr("udp",p)
if err != nil {
return err
}
ServerConn, err := net.ListenUDP("udp", ServerAddr)
if err != nil {
return err
}
defer ServerConn.Close()
n,addr,err := ServerConn.ReadFromUDP(b[:1024])
if err != nil {
return err
}
if n<1024 {
return fmt.Errorf("Only %d bytes could be read.", n)
}
Channels
package main
import "fmt"
func main() {
n := 2
// "make" the channel, which can be used
// to move the int datatype
out := make(chan int)
// run this function as a goroutine
// the channel that we made is also provided
go Square(n, out)
// Any output is received on this channel
// print it to the console and proceed
fmt.Println(<-out)
}
func Square(n int, out chan<- int) {
result := n * n
//pipes the result into it
out <- result
}
Defer, Panic, and Recover
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered", r)
}
}()
panic("make panic")
}
fmt Printing
// print integer
%b
base 2
%c
the character represented by the corresponding Unicode code point
%d
base 10
%o
base 8
%q
a single-quoted character literal safely escaped with Go syntax
%x
base 16, with lower-case letters for a-f
%X
base 16, with upper-case letters for A-F
%U
Unicode format: U+1234; same as "U+%04X"
// print string / general
%s
the uninterpreted bytes of the string or slice
%v
The value in a default format. When printing structs, the plus flag (%+v) adds field names.
// print bool
%t
the word true or false
// print float
%f
default width, default precision
%9f
width 9, default precision
%.2f
default width, precision 2
%9.2f
width 9, precision 2
%9.f
width 9, precision 0
Variable & Function Declarations
const country = "china"
// declaration without initialization
var age int
// declaration with initialization
var age int = 23
// declare and init multiple at once
var age, pincode int = 23, 577002
// type omitted, will be inferred
var age = 23
// simple function
func person() {
// shorthand, only within func bodies
// type is always implicit
age := 23
}
// Can have function with params
func person(firstName string, lastName string) {}
// Can have multiple params of the same type
func person(firstName, lastName string) {}
// Can return type declaration
func person() int {
return 23
}
// Can return multiple values at once
func person() (int, string) {
return 23, "vinay"
}
var age, name = person()
// Can return multiple named results
func person() (age int, name string) {
age = 23
name = "vinay"
return
}
var age, name = person()
// Can return function
func person() func() (string,string) {
area:=func() (string,string) {
return "street", "city"
}
return area
}
Encoding
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
)
type Employee struct {
Name string `json:"name" xml:"name"`
Age int `json:"age" xml:"age"`
}
func main() {
emp := Employee{
Name: "andan.h",
Age: 27,
}
// Marshal: refers to the process of converting
// the data or the objects into a byte-stream
jsonData, _ := json.Marshal(emp)
fmt.Println(string(jsonData))
xmlData, _ := xml.Marshal(emp)
fmt.Println(string(xmlData))
// Unmarshal: refers to the reverse process of
// converting the byte-stream back to data or object
json.Unmarshal(jsonData, &emp)
fmt.Println(emp)
}
Loops
// There only for, no while, no until
for i := 1; i < 10; i++ {
}
for ; i < 10; { // while - loop
}
for i < 10 { // omit semicolons
}
for { //omit the condition ~ while (true)
}
Switch
switch operatingSystem {
case "darwin":
fmt.Println("Mac OS Hipster")
// cases break automatically
case "linux":
fmt.Println("Linux Geek")
default:
// Windows, BSD, ...
fmt.Println("Other")
}
Hello World
package main
import "fmt"
func main() {
fmt.Println("Hello, World!!")
}
Running
$ cd $HOME/go/src/hello
$ go run main.go
Hello, World!!
$ go build
$ ./hello
Hello, World!!
本文由 络壳 原创或整理,转载请注明出处