#Sometimes when I look at other people's Go code, I find that some of them use pointers in the code, and some don't. (Recommended learning: go)
Suppose there is a structure type called Person, and it is found that some methods use func methodA (*person Person) as a parameter, or use func *( person Person) methodA() is used as the structure's own method, that is, the person structure can directly call methodA, but using a pointer.
Or you can see the usage of var personMap map[string]*Person in the map structure
If you transfer from java to golang, it may not be easy to understand. Because there are no pointers in the Java world, you can just pass it directly and use it. However, you need to pay attention to many things when going to golang.
So when should you use it? Why is it needed in some places?
If you don’t use pointers, you cannot assign values to the structure in some cases. Let’s look at a piece of code. This code does not use any pointers and first defines a bunch of objects for testing.
type Person struct { //person结构体,包含年龄,名称,车 age int name string car Car } type Car struct { //person名下的车 name string //车的名字 } var personMap map[string]Person //一个存放person的map func setName(person Person, name string) { //给参数person设置名字 person.name = name } func (person Person) setName(name string) { //设置名字 person.name = name } func printName(person Person){ //打印person的名字 fmt.Println(person.name) } func (person Person)printName(){ //结构体person自己支持打印名字 fmt.Println(person.name) }
Then write the main method. I will comment the printed results in the code. I can find that the assignment fails in many cases.
func main() { person := Person{} fmt.Println(person) //{0 {}} person.age = 12 person.name = "小明" person.car = Car{"宝马"} fmt.Println(person) //{12 小明 {宝马}},正常赋值给person变量,因为这是在方法里面的变量 setName(person, "小红") fmt.Println(person) //{12 小明 {宝马}},小红赋值失败,传递给setName方法的person没有赋值成功 person.setName("小红") fmt.Println(person) //{12 小明 {宝马}},person自己setName,还是失败 personMap = make(map[string]Person) personMap["test"] = person person = personMap["test"] person.name = "小红" fmt.Println(person) //{12 小红 {宝马}},从map中取出person,给小红赋值成功 for _, value := range personMap { //遍历map fmt.Println(value)//{12 小明 {宝马}},打印的还是小明,而不是小红,说明上面personMap["test"]对象赋值失败 } }
Next, change it to use a pointer
type Person struct { age int name string car Car } type Car struct { name string } var personMap map[string]*Person func setName(person *Person, name string) { person.name = name } func (person *Person) setName(name string) { person.name = name } func printName(person Person){ fmt.Println(person.name) } func (person Person)printName(){ fmt.Println(person.name) }
Modify the main method and use the & address character
func main() { person := Person{} fmt.Println(person) //{0 {}} person.age = 12 person.name = "小明" person.car = Car{"宝马"} fmt.Println(person) //打印{12 小明 {宝马}} setName(&person, "小红") fmt.Println(person) //{12 小红 {宝马}}, 成功赋值! person.setName("小黑") fmt.Println(person) //{12 小黑 {宝马}}, 成功赋值! personMap = make(map[string]*Person) personMap["test"] = &person person = *personMap["test"] person.name = "小兰" fmt.Println(person) //{12 小兰 {宝马}},成功赋值! for _, value := range personMap { fmt.Println(value) //&{12 小兰 {宝马}},读取的也是正确的小兰 } }
So we have To conclude, when we need to modify the variable content of the structure, the structure variable parameters passed in by the method need to use pointers , that is, when the address of the structure needs to modify the variables of the architecture in the map , you also need to use the structure address as the value of the map
If you just read the structure variable, you can pass the reference directly without using the pointer
*type The type variable here stores an address. This needs to be clear. You need to use &type to get the address.
The above is the detailed content of Can golang not use pointers?. For more information, please follow other related articles on the PHP Chinese website!

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

Golang ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment