Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common mistakes in Go development

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what are the common mistakes in Go development". In the daily operation, I believe that many people have doubts about the common mistakes in Go development. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "what are the common mistakes in Go development?" Next, please follow the editor to study!

1. Infinite recursive call

A recursive call to its own function requires an exit condition. Otherwise, it will be recursive forever until the system runs out of memory.

This problem may be caused by common errors, such as forgetting to add an exit condition. It can also happen "intentionally". Some languages have tail call optimizations, which make some infinite recursive calls safe to use. The tail call optimization allows you to avoid assigning new stack frames to the function because the calling function returns the value it gets from the called function. The most common use is tail recursion, where recursive functions written to take advantage of tail call optimization can use constant stack space. However, Go does not implement tail call optimization, and you will eventually run out of memory. However, this problem does not apply to the generation of new goroutine.

two。 Assign to nil Map

Before adding any elements, you need to initialize the mapping using the make function (or map literal). Create a new empty mapping value make using the built-in function, which takes the map type and optional capacity prompt as parameters:

Make (map [string] int) make (map [string] int

The initial capacity does not limit its size: the map grows to accommodate the number of items stored in it, with the exception of nil Maps. A nil map is different in that you can add empty mappings without elements.

Bad mode:

Var countedData map [string] [] ChartElement

Good model:

CountedData: = make (map [string] [] ChartElement) 3. Method to modify the receiver

Methods that modify non-pointer receiver values can have adverse consequences. This is an error risk because the method may change the value of the method's internal receiver, but it is not reflected in the original value. To propagate changes, the recipient must be a pointer.

For example:

Type data struct {num int key * string items map [string] bool} func (d data) vmethod () {d.num = 8} func (d data) run () {d.vmethod () fmt.Printf ("% + v", d) / / Output: {num:1 key:0xc0000961e0 items:map [1:true]}}

If the num must be modified:

Type data struct {num int key * string items map [string] bool} func (d * data) vmethod () {d.num = 8} func (d * data) run () {d.vmethod () fmt.Printf ("% + v", d) / / Output: & {num:8 key:0xc00010a040 items:map [1:true]} 4. Unwanted values may be used in Goroutine

The scope variable in the loop is reused in each iteration; therefore, the goroutine created in the loop will point to the scope variable in the upper scope. In this way, goroutine can use variables with unwanted values.

In the following example, the values of index and value used in goroutine come from an external range. Because goroutine runs asynchronously, the values of index and value may (usually) be different from expected values.

MySlice: = [] string {"A", "B", "C"} for index, value: = range mySlice {go func () {fmt.Printf ("Index:% d\ n", index) fmt.Printf ("Value:% s\ n", value)} ()}

To overcome this problem, you must create a local scope, as shown in the following example.

MySlice: = [] string {"A", "B", "C"} for index, value: = range mySlice {index: = index value: = value go func () {fmt.Printf ("Index:% d\ n", index) fmt.Printf ("Value:% s\ n", value)} ()}

Another way to deal with this problem is to pass the value to goroutine as args.

MySlice: = [] string {"A", "B", "C"} for index, value: = range mySlice {go func (index int, value string) {fmt.Printf ("Index:% d\ n", index) fmt.Printf ("Value:% s\ n", value)} (index, value)} 5.Close is postponed before checking for possible errors

For the Close () method that implements the value defer of the interface, this is a common pattern for Go developers, io.Closer. For example, when opening a file:

F, err: = os.Open ("/ tmp/file.md") if err! = nil {return err} defer f.Close ()

But this mode is harmful to writable files because deferring a function call ignores its return value, and the Close () method may return an error. For example, if you write data to a file, after you call Close. This error should be handled explicitly.

Although you can continue without using it, defer you need to remember to close the file each time you finish your work. A better approach is for defer to use wrapper functions, as shown in the following example.

F, err: = os.Open ("/ tmp/file.md") if err! = nil {return err} defer func () {closeErr: = f.Close () if closeErr! = nil {if err = = nil {err = closeErr} else {log.Println ("Error occured while closing the file:", closeErr)}} () return err

When working on a team, it becomes important to review other people's code. DeepSource is an automated code review tool that manages the end-to-end code scanning process and automatically issues a pull request with a fix when a new commit or pull request is pushed.

Setting up DeepSource for Go is very simple. Once the setup is complete, an initial scan of the entire code base is performed to find the scope of improvements, fix them, and open the PR for these changes.

At this point, the study of "what are the common mistakes in Go development" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report