Go Series Tutorial--15. Pointer

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Welcome to the 15th tutorial [Golang Series Tutorial] (/SUBJECT/2). # # # What is a pointer? A pointer is a variable that stores the memory address of a variable. Pointer (https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-series/pointer-explained.png "pointer") as shown, The value of the variable ' B ' is ' 156 ' and the memory address of ' B ' is ' 0x1040a124 '. The variable ' a ' stores the address of ' B '. We'll call ' a ' pointing to ' B '. The type of the declaration pointer variable for # # # pointer is * * ' *t ' *, which points to a variable of type **t**. Next we write some code. "' Gopackage mainimport (" FMT ") func main () {b: = 255 var a *int = &b fmt. Printf ("Type of A is%t\n", a) fmt. PRINTLN ("Address of B is", a)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/A4VMLGXAY8) **&** operator is used to get the address of the variable. On line 9th of the above program we assign the address of ' B ' to the ' a ' of the ' *int ' * * type. We call ' a ' pointing to ' B '. When we print the value of ' a ', the address of ' B ' is printed. The program will output: ' ' Type of A is *int address of B is 0x1040a124 ' because B may be in memory anywhere, you should get a different address. # # # pointer's 0 value (Zero value) pointer to the 0 value is ' nil '. "' Gopackage mainimport (" FMT ") func main () {a: =/var b *int if b = = nil {fmt. Println ("B is", b) b = &a FMT. Println ("B after initialization is", B)}} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/YAEGHZGQE1) in the program above, ' B ' is initialized to ' nil ', then the address of ' a ' is assigned to ' B '. The program will output: ' ' B is <nil> b after initialisation is 0x1040a124 ' # # # The dereference of the pointer can get the value of the variable pointed to by the pointer. The syntax to dereference ' a ' is ' *a '. Using the following code, you can see how to use the dereference. "' Gopackage main import (" FMT ") func main () {b: = 255 A: = &b fmt. PRINTLN ("Address of B is", a) fmt. Println ("value of B is", *a)} ' [Online Run Program] (Https://play.golang.org/p/m5pNbgFwbM) on line 10th of the above program, we will ' a ' dereference and print its value. As expected, we will print out the value of ' B '. The program outputs: ' Address of B is 0x1040a124 value of B is 255 ' ' We'll write a program that modifies the value of B with a pointer. "' Gopackage mainimport (" FMT ") func main () {b: = 255 A: = &b fmt. PRINTLN ("Address of B is", a) fmt. Println ("value of B is", *a) *a++ FMT. PRINTLN ("New value of B is", b)} ' [Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/CDMVLPBNMB) in line 12th of the above program, we add ' a ' to the value 1, because ' a ' points to the ' B ', so the value of ' B ' has changed as well. So the value of ' B ' becomes 256. The program outputs: ' Address of B is 0x1040a124 value of B is 255 new value of B is 256 ' ' # # # to function pass pointer parameter ' ' Gopackage mainimport ("Fmt ") func Change (Val *int) {*val = 55}func main () {a: =. Fmt. Println ("Value of a before Function call was ", a) b: = &a change (b) fmt. Println ("Value of a after function call is", a)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/3N2NHRJJQN) in the above program in line 14th, we go to the function ' Change ' passed the pointer variable ' b ', while ' B ' stores the address of ' a '. The 8th line of the program uses the dereference within the ' change ' function, modifying the value of a. The program outputs: ' ' value of a before function call is the value of a after function call is 55 ' # # # do not pass an array of pointers to the function, but should use slices if we want to be inside the function Modifying an array and hoping to get a modified array where the function is called, one solution is to pass a pointer to the array to the function. "' Gopackage mainimport (" FMT ") func modify (arr *[3]int) {(*arr) [0] = 90}func Main () {a: = [3]int{89, all,} modify (&am P;a) fmt. Println (A)} "[Running Program Online] (HTTPS://PLAY.GOLANG.ORG/P/LOIZNCBCVS) in line 13th of the above program, we pass the address of the array to the ' modify ' function. In line 8th, we dereference ' arr ' in the ' modify ' function and assign ' 90 ' to the first element of the array. The program will output ' [90 90 91] '. * * ' a[x] ' is a shorthand for ' (*a) [x] ', so ' (*arr) [0] ' in the above code can be replaced with ' arr[0] ' * *. Let's rewrite the above code in shorthand form. "' Gopackage mainimport (" FMT ") func modify (arr *[3]int) {arr[0] = 90}func Main () {a: = [3]int{89, All-in-A,} modify (&a ) FMT. Println (A)} "[Online Run Program] (Https://play.golang.org/p/k7YR0EUE1G) The program will also output '[90 90 91] '. * * This method passes an array pointer parameter to the function and modifies the array within the function. Although it is effective, it is not the way that the Go language is customarily implemented. We'd better use [slice] (https://golangbot.com/arrays-and-slices/) to handle it. * * Next we'll use [slice] (https://golangbot.com/arrays-and-slices/) to rewrite the previous code. "' Gopackage mainimport (" FMT ") func modify (SLS []int) {sls[0] = 90}func Main () {a: = [3]int{89, *,] Modify (a[:]) FM T.println (A)} "[Online Running program] (Https://play.golang.org/p/rRvbvuI67W) in line 13th of the above program, we pass a slice to the ' modify ' function. In the ' modify ' function, we modify the first element of the slice to ' 90 '. The program will also output ' [90 90 91] '. * * So don't pass the array pointer again, but use the slice bar * *. The code above is more concise and more consistent with the Go language habit. # # # Go does not support pointer arithmetic go does not support pointer operations in other languages such as C. "' Gopackage MainFunc main () {b: = [...] INT{109, 111} P: = &b p++} "" [Online Run Program] (Https://play.golang.org/p/WRaj4pkqRD) The above program throws a compilation error: * * ' main.go:6: Invalid operation:p++ (non-numeric type *[3]int) ' * *. I created a program on [GitHub] (https://github.com/golangbot/pointers) that covers all the things we've discussed. This concludes the introduction to pointers. I wish you a pleasant stay. * * Previous tutorial-[string] (https://studygolang.com/articles/12261) * * * Next tutorial-[structure] (https://studygolang.com/articles/12263) * *

via:https://golangbot.com/pointers/

Author: Nick Coghlan Translator: Noluye proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

2,666 Reads

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.