- Go Systems Programming
- Mihalis Tsoukalos
- 320字
- 2021-07-02 18:07:59
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}
- Mastering Concurrency Programming with Java 8
- The Supervised Learning Workshop
- Java程序設計實戰教程
- Learning Real-time Processing with Spark Streaming
- Manga Studio Ex 5 Cookbook
- Web Scraping with Python
- 實戰Java程序設計
- 深入淺出Android Jetpack
- 微信公眾平臺開發:從零基礎到ThinkPHP5高性能框架實踐
- Learning SciPy for Numerical and Scientific Computing(Second Edition)
- Scala Reactive Programming
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- 打開Go語言之門:入門、實戰與進階
- 大話Java:程序設計從入門到精通
- Angular應用程序開發指南