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

When do you use Go pointers?

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

Share

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

When to use Go pointer, for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

Using pointers in Go code is not very friendly for beginners, especially when it is difficult to distinguish between usage scenarios.

I think one of the biggest misunderstandings when using pointers is that pointers in Go are very similar to pointers in C. However, this is not the case. Pointers don't work in Go the way they work in CAccord Cobalt +.

This article will explore how to use Go pointers (Go Pointer) correctly.

Wrong conclusion: better performance with pointers?

It is generally believed that when pointers are used, the application will run faster because this will avoid constant value replication. It's not surprising that we have the same idea in Go.

However, pointer passing in Go is usually slow. This is a result of Go being a language with garbage collection mechanisms. When you pass a pointer to a function, Go needs to perform escape analysis to determine whether the variable should be stored in the heap or in the stack. This has added some extra overhead, but other variables can be stored in the heap. When you store a variable in the heap, you lose time during GC execution.

A handy feature of Go is that you can check what the escape analysis has done by executing the command go build-gcflags= "- m". If you do this, Go will tell you whether a variable escapes to the heap:

. / main.go:44:20: greet... Argument does not escape./main.go:44:21: greeting escapes to heap./main.go:44:21: name escapes to heap

If a variable does not escape to the heap, it is on the stack. The stack does not need a garbage collector to clear variables, it only does push/pop operations.

If anything is passed in value, it will always be processed in the stack, which will not incur the overhead of garbage collection. (GC will run at the default settings. The less content in the heap, the less GC needs to do.

Now that you know that using pointers can degrade performance, when do you need to use pointers?

Copy large data structures

Does the pointer always show poor transmission of the ratio? That's obviously not the case. Pointers play a role when dealing with large data structures. This may make the cost of garbage collection offset by the cost of copying large amounts of data.

When I mention this, I am always asked, 'how old should that big data be'?

I don't think there is a fixed value here, and anything related to performance should be benchmarked. Go has built-in powerful benchmarking tools that can be used

Variability

The only way to modify function parameters is to pass a pointer. By default, changes to values are made on the copy. Therefore, these changes cannot be reflected in the function that calls it.

Look at the following code:

Type person struct {name string} func main () {p: = person {"Richard"} rename (p) fmt.Println (p)} func rename (p person) {p.name = "test"}

The output is Richard because the changes to person are made on its copy. If you want to change the value of the underlying person object, you need to use a pointer.

Func main () {p: = person {"Richard"} rename (& p) fmt.Println (p)} func rename (p * person) {p.name = "test"}

As above, output test. Variability is a scenario in which pointers are used in Go. Whether this is a good thing needs to be discussed.

API consistency

Use pointers to maintain the latest values. This keeps the API consistent, even if not all methods change its value.

So, this:

Func (p * person) rename (s string) {p.name = s} func (p * person) printName () {fmt.Println (p.name)}

Better than

Func (p * person) rename (s string) {p.name = s} func (p person) printName () {fmt.Println (p.name)}

Although you don't need to use pointers in printName for consistency. But this will make API easier and avoid remembering exactly where references are needed.

Indicates missing

General values have a default zero value when used. But there are situations where you need to know that something is missing or unfilled. For example, a structure contains a student's test score. If the structure is empty and has a score of 0, does it mean that the student did not do well in the exam, or did not take the exam at all?

The default zero value of the pointer is the nil pointer, which indicates that no value is set. This requirement can also be achieved as follows:

Type exam struct {score int present bool}

Use a separate present field to indicate that the student did not take the exam.

Why did I choose the value?

There will be some subjective consciousness in it. Different people have different understandings of programming, so we don't need to have the same idea.

I believe it makes sense to have the Go median as default as possible. This may not apply to all scenarios, but in my case it can avoid causing a big accident. Using values instead of pointers will not cause Tony Hoare's "million dollar error" due to null pointers.

The default zero value is useful to avoid a large number of declarations.

Another benefit is that variability causes far more problems than it solves. The side effects of variability on functions also make debugging more difficult. This mutation can be avoided by letting the function return the modified structure.

Rewrite the previous example

Func main () {p: = person {"richard"} p = rename (p) fmt.Println (p)} func rename (p person) person {p.name = "test" return p}

This is also how append works, so it's no stranger.

X: = [] int {1pm 2} x = append (x, 3) x = append (x, 4)

In view of the security of pointers, and the processing of values is faster than pointers, the use of pointers requires repeated consideration.

This is the answer to the question about when to use the Go pointer. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

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