Golang Language Foundation VI: string, pointer

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

Golang Language Foundation VI: string, pointer

Golang Language Base series:

    • Golang one of the language foundations: type, variable, constant
    • Golang Language Foundation II: For, IfElse, switch
    • Golang Language Foundation Three: array, slice
    • Golang Language Foundation IV: MAP, RANGE
    • Golang Language Foundation: function
    • Golang Language Foundation VI: string, pointer
    • Golang Language Foundation VII: struct, method
    • Golang Language Foundation Eight: interface
    • Golang Language Foundation IX: Error, panic, recover
    • Golang Language Foundation: Goroutine, Channel

String typestring

The string is defined in the Golang source file runtime.h as follows:

structString{byte*str;intgolen;};

As you can see, the inside contains an byte array of type Golang in UTF-8 encoding. In contrast to the character array of C/s + +, Golang's character array has the following characteristics:

    • stringThe 0 value of the type is an empty string.
    • Cannot get byte element pointer with ordinal, &s[i] is illegal.
    • stringis an immutable type whose internal character array that stores data cannot be modified. If you want to modify, you need to convert the string object to a rune type (if the string contains non-ASIC characters) or byte a type (if the string consists of an ASIC character) slice . The modified character array will reallocate memory to be saved in a new string object.
    • The tail of the byte array does not contain\0

stringlet's look at an example of how to use it:

 Package MainImport "FMT"func Main() {//Default String type Object 0 value is an empty string, tail does not contain 'var emptyStr stringFMT.Println("EMPTYSTR is:", emptyStr)FMT.Println("Len (EMPTYSTR) is:", Len(emptyStr))//declares a string object and initializes it, using the subscript to access it. //Note that if the string contains non-ASIC characters such as Chinese, then using the subscript index will result in inconsistent resultsThe //string is UTF-8 encoded, so the non-ASIC character is more than one byte, and the subscript is used to obtain the contents of each byte. Str := "I like high round round"FMT.Println("String object is:", Str)FMT.Println("Len (str) =:", Len(Str))FMT.Println("str[1]:", Str[1])//Use ' syntax to declare a string without escapingStr = ' Ilovegolang 'FMT.Println("STR:", Str)//Modify the string, and note that the strings are converted to ' slice ' objects of ' rune ' and ' byte ' respectively. //Their lengths are unequal, and the ' Rune ' slice object has a length equal to the number of characters in the original ' String ' object. The length of the //' byte ' slice object is equal to the number of bytes that the original ' string ' object occupies in memory, and the value of ' string ' object obtained by ' Len ' is equal//If there are non-ASIC codes in the ' String ' object, the lengths of the two are not equal. //So to ensure compatibility, it is best to convert the ' string ' object to a ' rune ' slice object and modify it. Str = "I like high round round"FMT.Println("Before modification, str:", Str)FMT.Println("Len (str) =:", Len(Str))Rune_str := []Rune(Str)Byte_str := []byte(Str)FMT.Println("Len ([]rune (str)) =", Len(Rune_str))FMT.Println("Len ([]byte (str)) =", Len(Byte_str))Rune_str[7] = ' Fan 'Rune_str[8] = ' Ice 'Rune_str[9] = ' Ice 'FMT.Println("After modification, str:", string(Rune_str))//The character constant in single quotation marks is ' rune ' type, followed by type int32V_char := ' G 'FMT.Printf("The type of V_char is%T\ n", V_char)}

Put the above code into the source file String.go and use go run string.go to see the following input:

emptyStr is:  len(emptyStr) is:  0string object is:  I like 高圆圆len(str) = :  16str[1]:  32str:  I      Love      GolangBefore modification, str:  I like 高圆圆len(str) = :  16len([]rune(str)) =  10len([]byte(str)) =  16After modification, str:   I like 范冰冰The type of v_char is int32

Pointer typepointer

The pointers in Golang and C + + are in the same place:

    • Pointer *t
    • Pointer to Pointer **t
    • By operator * access to the object pointed to by the pointer, & take the address of the object

The different places are:

    • The default value of the pointer is nil , notNULL
    • Pointers cannot be added and reduced, and members of the objects referred to by pointers use . access instead of->
    • Use to unsafe.Pointer convert pointers to different types of objects
    • Pointers cannot be performed + and - operated to ensure security.

Examples of usage are as follows:

 Package MainImport ("FMT""unsafe")func Main() {//Check the pointer object with a value of nil 0var P *intFMT.Println("The zero value of a pointer is:", P)//Pointer to pointerpp := &PFMT.Printf("The type of a pointer points another pointer is:%T\ n", pp)//Pointer object assignmentIntvar := 100000000P = &IntvarFMT.Println("After assignment, p is:", P)FMT.Println("The value pointer p points is:", *P)//Use unsafe. The Pointer method converts a pointer of type to Pointer//Pointer can be converted to any type of pointer. //Note Because int is an alias of Int32, it takes up 4 bytes, so we convert it to a ' byte ' array pointer containing 4 byte elementsvar STRP *[4]byteSTRP = (*[4]byte)(unsafe.Pointer(P))FMT.Println(" after\"( *[4]byte) (unsafe. Pointer (p))\", *[4]byte pointer strp is: ", STRP)FMT.Println(" after\"( *[4]byte) (unsafe. Pointer (p))\", *[4]byte pointer strp points to: ", *STRP)//Pointer to object content using '. ' Instead of ' to ' to accesstype User struct {name string}Userp := &User{"Xiaohui",}FMT.Println("Before, the value userp points to be:", *Userp)Userp.name = "Ross"FMT.Println(After change , the value userp points to is: ", *Userp)}

Put the above code into the source file Pointer.go and use go run pointer.go to see the following input:

The zero value of a pointer is:  <nil>The type of a pointer points another pointer is: **intAfter assignment, p is:  0xc20800a240The value pointer p points is:  100000000After "(*[4]byte)(unsafe.Pointer(p))", *[4]byte pointer strP is:  &[0 225 245 5]After "(*[4]byte)(unsafe.Pointer(p))", *[4]byte pointer strP points to:  [0 225 245 5]Before change, The value userP points to is:  {Xiaohui}After change,  The value userP points to is:  {Ross}

About unsafe.Pointer , suggest reading this article, inside did a very good summary.

Resources

    • The Go programming Language
    • Learn the Chinese version of the Go language
    • Go in Action Chinese version
    • The Go Chinese version
    • Go by Example
    • Organizing Go Code
    • Testing techniques
    • Go language Sharing
    • Go Learning Notes
    • Go Language Introduction
    • Tony Bai's Blog

--EOF--

    • Golang Language Foundation of the five: function→
    • ←golang Language Foundation VII: struct, method

Disclaimer: This article uses the BY-NC-SA protocol to authorize. Reprint please specify turn from: Golang Language Foundation Six: string, pointer

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.