Home > Article > Backend Development > Here are the pitfalls you need to pay attention to when using Go!
This article is provided by the golang tutorial column to introduce you to some pitfalls that you need to pay attention to when using Go. I hope it will be helpful to friends in need!
Pitfalls of Go that need to be noted
Pitfalls that need to be noted
The advantage of Go lies in its convenient coroutine programming and its strong performance in network processing. . However, in order to pursue simplicity of use, the Go language is very different from other languages. Here are some main pitfalls to pay attention to:
1. The class may accidentally implement an interface (it happens to contain the interface of this interface) implementation), the semantics of the implementation may differ from what is expected by the interface contract.
2. := and = are easy to confuse
3. The zero value problem of the class. If Map has a zero value, it can be queried but cannot be assigned.
4. Reference type If the value is passed, the original value will still be modified. What are the reference types
5, slice trap, if the capacity is sufficient, it is passed by reference
6, nil interface value
Pit 2~Pit 6 code Examples are as follows:
package main import ( "fmt" "time" ) func catchError() { if err := recover(); err != nil { fmt.Println(err) } } func hole2() { a := 1 if time.Now().Year() > 2020 { a := 2 // 一不小心加了一个冒号 println(a) } println(a) } func hole3() { defer catchError() var m0 map[string]string println("key:", m0["key"]) m0["key"] = "val" // 报错:assignment to entry in nil map } type Hole4 struct { Name string Slices []string MyMap map[string]string Channel chan int } func hole4() { a := Hole4{ Name: "a", Slices: []string{"a"}, MyMap: map[string]string{"key": "a"}, Channel: make(chan int), } go func() { for n := range a.Channel { fmt.Println(n) } }() b := a b.Name = "b" b.Slices[0] = "b" b.MyMap["key"] = "b" b.Channel <- 999 fmt.Println(a) fmt.Println(b) } func hole5() { slice1 := make([]string, 1, 1) slice1[0] = "1" temp1 := slice1 temp1 = append(temp1, "1") temp1[0] = "2" fmt.Println(slice1) slice9 := make([]string, 1, 9) slice9[0] = "1" temp2 := slice9 temp2 = append(temp2, "1") temp2[0] = "2" fmt.Println(slice9) } type Cache interface { Name() } type RedisCache struct{} func (RedisCache) Name() {} func hole6() { defer catchError() var redis1 *RedisCache = nil var redis2 Cache = redis1 if redis2 != nil { println("entering...") redis2.Name() // 报错:nil pointer dereference } } func main() { hole2() hole3() hole4() hole5() hole6() }
The above is the detailed content of Here are the pitfalls you need to pay attention to when using Go!. For more information, please follow other related articles on the PHP Chinese website!