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

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.
主站蜘蛛池模板: 安西县| 禄劝| 教育| 兴海县| 凤冈县| 全州县| 广东省| 瑞安市| 轮台县| 新宾| 京山县| 中宁县| 胶南市| 红原县| 武邑县| 肥东县| 水城县| 繁峙县| 兰考县| 时尚| 冷水江市| 云龙县| 凤山市| 木兰县| 瑞昌市| 海伦市| 加查县| 镇坪县| 奉新县| 绍兴市| 建瓯市| 如东县| 闸北区| 伊金霍洛旗| 景宁| 嘉禾县| 广丰县| 久治县| 全椒县| 永昌县| 青州市|