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

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.
主站蜘蛛池模板: 琼海市| 峡江县| 常德市| 皋兰县| 乌什县| 伊川县| 克山县| 安平县| 民勤县| 天全县| 桦甸市| 门源| 新丰县| 繁峙县| 山阳县| 盐池县| 鞍山市| 盈江县| 昭苏县| 西宁市| 资中县| 收藏| 衡水市| 宜丰县| 太谷县| 阿巴嘎旗| 惠州市| 南宁市| 丹巴县| 稻城县| 益阳市| 三亚市| 郎溪县| 舞钢市| 原平市| 平湖市| 北票市| 陇西县| 西乡县| 延川县| 潮安县|