官术网_书友最值得收藏!

Using pointer variables in functions

Pointers are memory addresses that offer improved speed in exchange for difficult-to-debug code and nasty bugs. C programmers know more about this. The use of pointer variables in Go functions is illustrated inside the pointers.go file, which can be divided into two main parts. The first part contains the definition of two functions and one new structure named complex:

func withPointer(x *int) { 
   *x = *x * *x 
} 
 
type complex struct { 
   x, y int 
} 
 
func newComplex(x, y int) *complex { 
   return &complex{x, y} 
} 

The second part illustrates the use of the previous definitions in the main() function:

func main() { 
   x := -2 
   withPointer(&x) 
   fmt.Println(x) 
 
   w := newComplex(4, -5) 
   fmt.Println(*w) 
   fmt.Println(w) 
} 

As the withPointer() function uses a pointer variable, you do not need to return any values because any changes to the variable you pass to the function are automatically stored in the passed variable. Note that you need to put & in front of the variable name to pass it as a pointer instead of as a value. The complex structure has two members, named x and y, which are both integer variables.

On the other hand, the newComplex() function returns a pointer to a complex structure, previously defined in pointers.go, which needs to be stored in a variable. In order to print the contents of a complex variable returned by the newComplex() function, you will need to put a * character in front of it.

Executing pointers.go generates the following output:

$ go run pointers.go
4
{4 -5}
&{4 -5}
I do not recommend the use of pointers to amateur programmers outside of what is required by the libraries you use because they might cause problems. However, as you get more experienced, you might want to experiment with pointers and decide whether you want to use them or not depending on the problem you are trying to solve.
主站蜘蛛池模板: 漳平市| 大足县| 澎湖县| 特克斯县| 双江| 平罗县| 兰州市| 盐池县| 当涂县| 敖汉旗| 华池县| 泰安市| 清苑县| 石门县| 奎屯市| 濉溪县| 襄樊市| 西盟| 莱阳市| 新宾| 东辽县| 麻栗坡县| 柘荣县| 揭东县| 新竹县| 寻乌县| 孟州市| 内江市| 得荣县| 沈阳市| 农安县| 长海县| 报价| 江华| 克拉玛依市| 石家庄市| 嫩江县| 高要市| 通城县| 招远市| 陇南市|