Introduce¶
bullet points¶
- capital letter: exported function. like P in
fmt.Println
- naming with camel case. as
topPrice
orRetryConnection
- abbreviate for obvious names.
go build/go run/go fmt/go version
log.Fatal(err)
- understand the scope and block
- learn condition and loop (
for/break/continue
) fmt
containsPrintln, Printf...
with some%s, %f, %d, %t, %%...
errors.Error
anderr := fmt.Errorf()
&variable
=> pointer,*pointer
=> the value of the pointer.reflect.TypeOf(&variable)
=>pointer type
- package:
package clause + import section + actual code
- nameing conventions:
abbreviated
/one word
/local variable conflict
go install **
andimport "greeting/deutsch"
- change ws:
GOPATH
got get github.com/headfirstgo/keyward
go doc strconv
- add doc comments:
add comments before function or package
, thenpackage/functiion coments
godoc -http=:6060
?for i, v := range arr{}
- be caution:
append
slice vs array.
variadic function: ellipsis(...)
myMap := make(map[string]int)
struct and type and type embededded
func (m MyType) Method(m int) returnType
SetX, X(), encapsulation with exported and unexported.
interface
snippets¶
-
condition
if true && true { fmt.Println("true") }else{ fmt.Println("error") }
-
block and scope
var status string if grade > 10 { status = 1 }else{ status = 2 } fmt.Println("A grade of", grade, "is", status)
-
loop
for x := 1; true; x++ { fmt.Println(x) } var x int for x=1; x< 6; x++ { fmt.Println(x) } fmt.Pintln(x)
-
error
func squareRoot(number float64) (float64, error) { if number < 0 { return 0, fmt.Errorf("can't get square root of negative number") } return math.Sqrt(number), nil } root, err := squareRoot(-9.4)
-
pointer
myInt := 4 myPointer := &myInt *myPointer = 8 // become 8 fmt.Println(*myPointer) // 8 fmt.Println(myInt) // 8 func createPointer() *float64{ var myFloat = 93.4 return &myFloat } var myFloatPointer *float64 = createPointer() fmt.Println(*myFloatPointer)
-
array
var myArray [5]int = [5]int{1,2,3,4,5} myNotes := [3]string{"1", "2", "3"} fmt.Println(myArray) fmt.Println(myNotes[2]) for index, _ := range myNotes { fmt.Println(index) }
-
append
8. variadic functionfunc main() { s1 := []string{"s1"} s2 := append(s1, "s2") s3 := append(s2, "s3") s4 := append(s3, "s4") s4[0] = "X" fmt.Println(s1, s2, s3, s4) } //[s1] [s1 s2] [X s2 s3] [X s2 s3 s4]
func severalInts(numbers ...int){ fmt.Println(numbers) } func main(){ severalInts(1) severalInts(1,2,3) }
-
map
func main() { eles := make(map[int]string) eles[1] = "a" fmt.Printf("%#v\n", eles[1]) fmt.Printf("%#v\n", eles[12]) var ok bool var value string value, ok = eles[1] fmt.Println(value, ok) delete(eles, 1) for key, value := range eles { fmt.Println(key, value) } }
-
struct and type
type pair struct { name string age int sex bool } func doubleAge(p *pair) { p.age *= 2 } func main() { var aStruct pair aStruct.name = "dean" aStruct.age = 15 aStruct.sex = true fmt.Printf("%#v", aStruct) doubleAge(&aStruct) fmt.Printf("%#v", aStruct) }
11.