Error on page 52nd of Go Web Programming: string is not a pointer-like type

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

<< Go Web Programming >> book on page 52nd says:

In the Go language, the implementation mechanism of the three types of string,slice,map is similar to pointers, so it can be passed directly without taking the address and passing the pointer.

It is wrong to set this argument on a string.

Package Mainimport "FMT" Func add1 (a string) string {a = a + "Simida" return A}func Main () {x: = "I am Jon" FMT. Println ("x =", x) x1: = ADD1 (x) fmt. Println ("x + 1 =", x1) fmt. Println ("x =", x)/*output:x =  I am Jonx + 1 =  I am Jon simidax =  I Am jon*/}

In the above example, the value of x does not change after calling the function Add1 ().

Package Mainimport "FMT" func add1 (a *string) string {*a = *a + "Simida" return *a}func Main () {x: = "I am Jon" FMT. Println ("x =", x) x1: = Add1 (&x) fmt. Println ("x + 1 =", x1) fmt. Println ("x =", x)/*output:x =  I am Jonx + 1 =  I am jon Simidax =  I am Jon simida*/}

With pointer passing, the X value changes after the function is called.

Thus, the implementation mechanism of the string type is not analogous to a pointer.

The implementation mechanism of slice and map is similar to pointers, so it is not necessary to take an address to pass pointers.

Package Mainimport "FMT" func add1 (A []int) []int {to K, V: = Range a {a[k] = v + 1}return A}func Main () {x: = make ([]int, 2, 6) fmt. Println ("x =", x) x1: = ADD1 (x) fmt. Println ("x + 1 =", x1) fmt. Println ("x =", x)/*output:x =  [0 0]x + 1 =  [1 1]x =  [1 1]*/}

Package Mainimport ' FMT ' func add1 (a map[string]int) Map[string]int {for k, V: = Range a {a[k] = v + 1}return a}func Main () {x: = map[string]int{"A": 0, "B": 0}fmt. Println ("x =", x) x1: = ADD1 (x) fmt. Println ("x + 1 =", x1) fmt. Println ("x =", x)/*output:x =  map[a:0 b:0]x + 1 =  map[a:1 b:1]x =  map[a:1 b:1]*/}

Related Article

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.