search
HomeBackend DevelopmentGolangDo you know when to use Go pointers?

Do you know when to use Go pointers?

Sep 24, 2021 pm 03:08 PM
gopointer

This article is provided by the go language tutorial column to introduce to you under what circumstances use Go pointer (Go Pointer). I hope it will be helpful to friends in need!

Do you know when to use Go pointers?

The use of pointers in Go code is not very friendly to novices, especially when it is difficult to distinguish usage scenarios.

I think one of the biggest misunderstandings when using pointers is that pointers in Go are very similar to pointers in C language. However, that is not the case. Pointers don't work in Go the same way they do in C/C.

This article will discuss how to use Go pointers correctly.

Wrong conclusion: Using pointers is better?

It is generally believed that applications will run faster when using pointers because they avoid copying values ​​all the time. It’s no surprise that in Go we have the same idea.

However, pointer passing in Go is generally slower than value passing. This is a consequence of Go being a garbage-collected language. When you pass a pointer to a function, Go needs to perform escape analysis to determine whether the variable should be stored on the heap or the stack. This already adds some extra overhead, but otherwise the variables can be stored in the heap. When you store a variable in the heap, you also lose time while the GC is executing.

A convenient feature of Go is that you can check what 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 stays on the stack. The stack does not need a garbage collector to clear variables, it only does push/pop operations.

If any content is passed by value, it will always be processed on the stack, which will not cause garbage collection overhead. (The GC will run by default. Less content in the heap means the GC has less to do).

Now you know, using pointers will reduce performance, so when needuse pointers?

Copying large data structures

Do pointers always perform worse than value transfer? That's obviously not the case. When dealing with large data structures, pointers come into play. This may cause the cost of garbage collection to be offset by the cost of copying large amounts of data.

When I mention this, I’m always asked ‘how big should that big data be’?

I think there is no fixed value here. Anything related to performance should be benchmarked. Go has built-in powerful benchmarking tools, which can be fully utilized

Variability

The only way to modify function parameters is to pass pointers. By default, modifications to values ​​are performed on the copy. Therefore these modifications 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 modification to person is performed 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. Mutability is a situation where pointers are used in Go. Whether this is a good thing is up for debate.

API consistency

Use pointers to maintain the latest value. 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)
}

is better than

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

although for consistency there is no need to use pointers in printName. But this will make the API simpler and avoid having to remember where exactly a reference is needed.

Indicates missing

General values, when used, have a default value of zero. But there are scenarios where you need to know that something is missing or has an unfilled value. 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 test, or did not take the test at all?

The default zero value of a pointer is a nil pointer, which means no value is set. This requirement can also be implemented 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 do I choose value?

This is somewhat subjective. Different people have different understandings of programming, so we are not required to have the same concept.

I believe it makes sense to have default values ​​in Go as much as possible. This may not work in every situation, but in my case it prevented a big accident. Using a value instead of a pointer will not cause Tony Hoare's "million dollar mistake" due to a null pointer.

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

另一个好处是易变性造成的问题比它解决的问题多的得多。易变性给函数带来的副作用同时使得调试变得更加困难。 通过让函数返回修改之后的结构体,可以避免这种突变。

重写之前的例子

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

这也是 append 如何工作的,所以并不陌生。

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

鉴于指针的安全性,和值处理比指针处理更快,使用指针需要反复斟酌。

原文地址:https://medium.com/@meeusdylan/when-to-use-pointers-in-go-44c15fe04eac

译文地址:https://learnku.com/go/t/60923

The above is the detailed content of Do you know when to use Go pointers?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool