The pointers in the pits in the Golang are used

Source: Internet
Author: User

Today, when writing code, encountered a baffling error, debug a half-day, found that this is a very typical and easy to make mistakes. Remember it

Example code:

Package Mainimport"FMT"type AAstruct{x, yint}type BBstruct{member Aa}func main () {m:= []*aa{} pool:=[]BB {member:aa{x:1Y:1,},}, {member:aa{x:2Y:2,},}, {member:aa{x:3Y:3,},                },        }         for_, P: =Range Pool {m= Append (M, &p.member)} for_, Ele: =range m {ele.x= ele.x +1Ele.y= Ele.y +1         }         for_, Ele: =range M {fmt. Printf ("x=%d, y=%d\n", ele.x, Ele.y)}}

What is the result of the above code? Perhaps you will immediately answer is:

x=2, y=2

X=3, y=3

X=4, y=4

Run it and know that the answer is wrong. The correct operation results are:

X=6, y=6

X=6, y=6

X=6, y=6

So what's wrong? Originally in the array m, its three elements are the same pointer. Originally in the following code, Golang is a new variable p, each time the elements of the array

Assigned to this p, and the address of P is naturally constant, so the last element in M is the address of the member variable member of this p.

        for _, P: = range Pool {                = append (M, &p.member)        }

This example tells us that in an iterative operation of array/map in Golang, be careful if you need to access pointers to the array/map elements in the iteration. This type of bug is very difficult to detect.

The pointers in the pits in the Golang are used

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.