Get the App
SLTechnology News&Howtos  ›  Development  › 

Which pits should be paid attention to when using Go

Shulou Source: shulou.com Published: 2022-06-02 06:34:55 10月01日 Update

This article introduces the relevant knowledge of "which pits to pay attention to when using Go". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Go needs to pay attention to the pit

Need to pay attention to the pit

The advantage of Go lies in its convenient co-programming and strong performance in network processing. But the Go language is different from other languages in its pursuit of simplicity. Here are some of the main pitfalls:

1. The class may accidentally implement an interface (which happens to contain the implementation of this interface), and the semantics of the implementation may be different from that expected by the interface contract.

2.: = and = are easily confused

3. The zero value problem of a class. If Map is zero, it can be queried but cannot be assigned.

4. If the value of the reference type is passed, the original value will still be modified. Which are reference types

5. Slice trap. If the capacity is sufficient, the reference is passed.

6. Nil interface value

An example of the code for pit 2 ~ pit 6 is as follows:

Package mainimport ("fmt"time") func catchError () {if err: = recover () Err! = nil {fmt.Println (err)}} func hole2 () {a: = 1 if time.Now (). Year () > 2020 {a: = 2 / / accidentally added a colon println (a)} println (a)} func hole3 () {defer catchError () var m0 map [string] string println ("key:" M0 ["key"]) M0 ["key"] = "val" / / error: 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

Tags: Interface different content situation more knowledge type language primitive practical learned and then carelessness code advantage colon dilemma contract actual capacity Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn macOS Shulou Information Shulou Technology Apple