This is the 19th day of my participation in the First Challenge 2022, for more details: First Challenge 2022 “.

Rune Is the alias of INT32 (-2147483648 to 2147483647) and contains more characters than byte (-128 to 127). Because rune can represent a larger range of characters, it can handle all characters, including Chinese characters. Rune can be used to calculate Chinese characters at ordinary times.

When we have Chinese in our data, we must pay attention to rune processing.

Len (), rounding

Len () returns the number of byte bytes, 3 bytes for a Chinese character

S := "Hello king "sHello := "Hello" sWang :=" king "// Len () gets the number of bytes fmt.println (len(s)) fmt.println (len(sHello)) fmt.Println(len(sWang))Copy the code

The output is 8, 5, and 3

Looping string

S := "Hello "for I := 0; i < len(s); i++ { fmt.Printf("%c\n", s[i]) }Copy the code

Output result:

We found that English output can be normal, but Chinese output in this way will be garbled

Loop output Chinese string

We can go through the for range loop and pull out specific characters from the string

King s: = "Hello" for _, c: range s = {FMT. Printf (" % \ n "c, c) / /} % c charactersCopy the code

Output result:

String modification

String modifications cannot be made directly, but must be converted to rune slices and then modified

S2 := "rabbit" s3 := []rune(s2) // Force string into rune section s3[0] = 'big' // Note that single quotes are required here, Instead of the double quoted string fmt.println (string(s3)) // force rune s3 into a stringCopy the code

Output: White rabbit

The difference between characters and strings

C1: = "red" c2: = 'red' FMT) Printf (" c1 type: % T c2 type: % T \ n ", c1, c2) c3: = "H" c4: = 'H' FMT) Printf (" c4 c3 type: % T type: % T \ n ", c3, c4)Copy the code

Output result:

C1 type: String C2 type :int32 C3 type :string C4 type :int32Copy the code

Summary: We found that whenever double quotation marks are wrapped, the type is string, and whenever single quotation marks are wrapped, the type is int32, or rune. It has nothing to do with Chinese or English.

The alias for rune is INT32

Type conversion

N1 := 10 var f float64 f = float64(n1) FMT.Printf("f is of type: %T f is of value: %v\n", f,f)Copy the code

Output result:

The type of f is: float64 The value of f is: 10Copy the code

conclusion

String changes are converted to rune slices rather than directly modified as in PHP.

The last

Thanks for reading and welcome to like, favorites,coin(attention)!!