Go data types: strings and underlying character types

string

Basic use

In the Go language, string is a basic type. By default, it is a character sequence encoded by UTF-8. When the character is ASCII code, it occupies 1 byte. Other characters occupy 2-4 bytes as needed, such as Chinese encoding usually requires 3 bytes.

Declaration and initialization

The declaration and initialization of strings are very simple, for example:

var str string         // 声明字符串变量
str = "Hello World"    // 变量初始化
str2 := "你好,学院君"   // 也可以同时进行声明和初始化

Formatted output

You can also obtain the length of the specified string through the Go language's built-in len() function, and through fmt Printf provided by the package performs string formatting output:

fmt.Printf("The length of \"%s\" is %d \n", str, len(str)) 
fmt.Printf("The first character of \"%s\" is %c.\n", str, ch)

escape character

Go language strings do not support single quotes. String literals can only be defined through double quotes. If you want to escape specific characters, you can use \ to achieve it, just like Just like we escaped double quotes and newlines in strings above, the common characters that need to be escaped are as follows:

  • \n : newline character
  • \r : carriage return character
  • \t :tab key
  • \u or \U: Unicode character
  • \\ : backslash itself

Therefore, the output of the above printing code is:

The length of "Hello world" is 11 
The first character of "Hello world" is H.

In addition, you can include " in a string as follows:

label := `Search results for "Golang":`

multiline string

For multi-line strings, you can also build&#x with `

Guess you like

Origin blog.csdn.net/weixin_59284282/article/details/125496004