Go by Example:pointers

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The go language supports pointers, allowing you to pass variable values through references within the program.

Package Mainimport "FMT"//We use two functions: Zeroval and zeroptr to demonstrate the use of pointers//Zeroval functions have an int type parameter, this time passed to the function is the value of the variable. Zeroval gets a ival copy value from which function it is called. Func zeroval (ival int) {    ival = 0}//The argument to the ZEROPTR function is an int type pointer, which means a pointer passed to an int of the function. The *iptr from its memory address in the function body to obtain the current value corresponding to this address. Assigning a pointer to an dereference will change the value of the real address referenced by the pointer. Func zeroptr (iptr *int) {    *iptr = 0}func Main () {    I: = 1    fmt. Println ("initial:", i)    zeroval (i)    FMT. Println ("Zeroval:", i)//    by using the & operator to obtain the memory address of the variable///For example: &i is the pointer to the variable i    zeroptr (&i)    FMT. Println ("Zeroptr:", i)    //pointer type can also be printed out of the    FMT. PRINTLN ("pointer:", &i)}

Output

$ go Run pointers.goinitial:1zeroval:1zeroptr:0pointer:0x42131100

其中 zeroval in the main cannot be changed in a function i 's value, but zeroptr Yes, because it has a reference to the memory address of this variable.


Next example: Go by example:structs

English original


Welcome to scan the following QR code follow my public number: Codemanship (code)


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.