Go language data structure [string]

String

Brief introduction

  A string is a sequence of bytes can not be changed, the string is typically used to contain a human-readable text data. And the array is different, the elements of the string can not be modified, is a read-only byte array . While each string is also fixed, but is not a part of the length of the string type string. Since the source code is required in Go UTF8 encoding, resulting in the source string literals appearing in Go are generally UTF8 encoding.

  Go language strings corresponding to the underlying data is an array of bytes, the read-only attribute string prohibits changes to the underlying elements of the array of bytes in the program. String assignment just copied data and the corresponding address length, without causing copying of the underlying data ( key !! )

 

Underlying structure

Go substructure language strings in reflect.StringHeaderthe definition:

type StringHeader struct {
    Data uintptr
    Len  int
}

String structure consists of two information: a first string points to the underlying array of bytes, the second byte is the length of the string. In fact, the structure is a string, the string so assignment is reflect.StringHeaderreplication structure, and does not involve copying the underlying array of bytes. String array can be viewed as an array of structures.

We can see the string "Hello, world" itself corresponding memory structures:

Analysis can be found, "Hello, world", and the underlying data string arrays are exactly the same:

data := [...] byte{'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd',}

 

  

 

 

Guess you like

Origin www.cnblogs.com/lianzhilei/p/11521468.html