Home>Article>Backend Development> What does str mean in go language?

What does str mean in go language?

青灯夜游
青灯夜游 Original
2022-12-27 12:59:15 4229browse

In the Go language, str refers to "string", which is an immutable byte sequence. A string can contain any data, but is usually used to contain readable text. A string is a sequence of UTF-8 characters (when the character is a character in the ASCII code table, it occupies 1 byte, and other characters are based on Requires 2-4 bytes). String is a value type, and the value is immutable, that is, once a text is created, the content of this text cannot be modified again. More deeply, a string is a fixed-length array of bytes.

What does str mean in go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

In go language, str refers to "string".

A string is an immutable sequence of bytes. A string can contain arbitrary data, but is usually used to contain readable text. A string is a sequence of UTF-8 characters. (When the characters are in the ASCII code table, they occupy 1 byte, and other characters occupy 2-4 bytes as needed).

The internal implementation of strings in the Go language uses UTF-8 encoding, and each UTF-8 character can be easily accessed through the rune type. Of course, Go language also supports character-by-character access in traditional ASCII code.

UTF-8 is a widely used encoding format and the standard encoding for text files, including XML and JSON. Due to the uncertainty of the length of bytes occupied by this encoding, strings in the Go language may also occupy 1 to 4 bytes as needed, which is different from other programming languages such as C, Java or Python (Java always uses 2 bytes ). Go language does this not only to reduce memory and hard disk space usage, but also does not need to encode and decode text using the UTF-8 character set like other languages.

String is a value type, and the value is immutable, that is, after creating a certain text, the content of this text cannot be modified again. More deeply, a string is a fixed-length array of bytes.

Define string

You can use double quotes "" to define a string, and escape characters can be used in the string to achieve line breaks, Indentation and other effects, commonly used escape characters include:

  • \n: newline character

  • \r: carriage return

  • ##\t: tab key

  • \uor \U: Unicode character

  • \\: backslash itself

  • package main import ( "fmt" ) func main() { var str = "PHP中文网\nGo语言教程" fmt.Println(str) }
The running result is:

What does str mean in go language?##General comparison operators (==, !=, =, >) are compared by bytes in memory To implement string comparison, the result of comparison is the natural encoding order of strings. The length in bytes occupied by a string can be obtained through the function len(), such as len(str).

The content of the string (pure bytes) can be obtained through the standard indexing method. Write the index within square brackets []. The index starts counting from 0:

    The first byte of string str:
  • str[0]

  • The i-th byte:
  • str[i - 1]

  • Last 1 byte:
  • str[len(str)-1]

  • It should be noted that , this conversion scheme is only valid for pure ASCII code strings.

Note: It is illegal to obtain the address of a certain byte in a string, such as
&str[i]

.

String splicing character “ ”Two strings s1 and s2 can be spliced together through s := s1 s2 . Appends s2 to the end of s1 and generates a new string s.

You can splice strings in multiple lines in the code in the following way:

str := "Beginning of the string " + "second part of the string"

Tip: Because the compiler will automatically complete the semicolon at the end of the line, splicing The plus sign " " used in strings must be placed at the end of the first line.

You can also use "=" to splice strings:
s := "hel" + "lo," s += "world!" fmt.Println(s) //输出 “hello, world!”

Define multi-line stringsIn the Go language, the way of writing a string using double quotes is one of the common expressions of strings. It is called a string literal. This kind of double quote literal cannot span lines. If you want to use it in the source code When embedding a multi-line string in a string, you must use

`

backticks. The code is as follows:

const str = `第一行 第二行 第三行 \r\n ` fmt.Println(str)
Code running result:

What does str mean in go language?Backticks

`

is the key to the left of key 1 on the keyboard. The string between the two backticks will be assigned to the str variable as is.In this method, newlines between backticks will be treated as newlines in the string, but all escape characters will be invalid and the text will be output as is.

Multi-line strings are generally used for embedded source code and embedded data. The code is as follows:

const codeTemplate = `// Generated by github.com/davyxu/cellnet/ protoc-gen-msg // DO NOT EDIT!{{range .Protos}} // Source: {{.Name}}{{end}} package {{.PackageName}} {{if gt .TotalMessages 0}} import ( "github.com/davyxu/cellnet" "reflect" _ "github.com/davyxu/cellnet/codec/pb" ) {{end}} func init() { {{range .Protos}} // {{.Name}}{{range .Messages}} cellnet.RegisterMessageMeta("pb","{{.FullName}}", reflect.TypeOf((*{{.Name}})(nil)).Elem(), {{.MsgID}}) {{end}} {{end}} }

这段代码只定义了一个常量 codeTemplate,类型为字符串,使用`定义,字符串的内容为一段代码生成中使用到的 Go 源码格式。

`间的所有代码均不会被编译器识别,而只是作为字符串的一部分。

字符串字面量

在Go语言中,字符串字面量是通过两种不同的方式创建的:

  • 使用双引号("":在这里,字符串字面量使用双引号("")创建。此类字符串支持转义字符,如下表所示,但不跨越多行。这种类型的字符串文字在Golang程序中被广泛使用。

转义符 描述
\\ 反斜杠(\)
\000 具有给定的3位8位八进制代码点的Unicode字符
\’ 单引号(')。仅允许在字符文字中使用
\” 双引号("")。仅允许在解释的字符串文字中使用
\a ASCII铃声(BEL)
\b ASCII退格键(BS)
\f ASCII换页(FF)
\n ASCII换行符(LF)
\r ASCII回车(CR)
\t ASCII标签(TAB)
\uhhhh 具有给定的4位16位十六进制代码点的Unicode字符。

具有给定的8位32位十六进制代码点的Unicode字符。
\v ASCII垂直制表符(VT)
\xhh 具有给定的2位8位十六进制代码点的Unicode字符。
  • 使用反引号('':此处,字符串文字是使用反引号('')创建的,也称为raw literals(原始文本)。原始文本不支持转义字符,可以跨越多行,并且可以包含除反引号之外的任何字符。通常,它用于在正则表达式和HTML中编写多行消息。

package main import "fmt" func main() { //创建并初始化 //带有字符串文字的变量 //使用双引号 My_value_1 := "Welcome to nhooo" //添加转义字符 My_value_2 := "Welcome!\nnhooo" //使用反引号 My_value_3 := `Hello!nhooo` //添加转义字符 //原始文本 My_value_4 := `Hello!\nnhooo` //显示 fmt.Println("String 1: ", My_value_1) fmt.Println("String 2: ", My_value_2) fmt.Println("String 3: ", My_value_3) fmt.Println("String 4: ", My_value_4) }

输出:

What does str mean in go language?

关于字符串的要点

  • 字符串是不可变的:在Go语言中,一旦创建了字符串,则字符串是不可变的,无法更改字符串的值。换句话说,字符串是只读的。如果尝试更改,则编译器将引发错误。

//字符串是不可变的 package main import "fmt" func main() { //创建和初始化字符串 //使用简写声明 mystr := "Welcome to nhooo" fmt.Println("String:", mystr) /* 果你试图改变字符串的值,编译器将抛出一个错误,例如, cannot assign to mystr[1] mystr[1]= 'G' fmt.Println("String:", mystr) */ }

输出:

What does str mean in go language?

  • 如何遍历字符串?:您可以使用for range循环遍历字符串。此循环可以在Unicode代码点上迭代一个字符串。

语法:

for index, chr:= range str{ // 语句.. }

在这里,索引是存储UTF-8编码代码点的第一个字节的变量,而chr是存储给定字符串的字符的变量,str是字符串。

//遍历字符串 //使用for范围循环 package main import "fmt" func main() { //字符串作为for循环中的范围 for index, s := range "nhooo" { fmt.Printf("%c 索引值是 %d\n", s, index) } }

输出:

What does str mean in go language?

  • 如何访问字符串的单个字节?:字符串是一个字节,因此,我们可以访问给定字符串的每个字节。

//访问字符串的字节 package main import "fmt" func main() { //创建和初始化一个字符串 str := "Welcome to nhooo" //访问给定字符串的字节 for c := 0; c < len(str); c++ { fmt.Printf("\n字符 = %c 字节 = %v", str[c], str[c]) } }

What does str mean in go language?

  • 如何从切片创建字符串?:在Go语言中,允许您从字节切片创建字符串。

//从切片创建一个字符串 package main import "fmt" func main() { //创建和初始化一个字节片 myslice1 := []byte{0x47, 0x65, 0x65, 0x6b, 0x73} //从切片创建字符串 mystring1 := string(myslice1) //显示字符串 fmt.Println("String 1: ", mystring1) //创建和初始化一个符文切片 myslice2 := []rune{0x0047, 0x0065, 0x0065, 0x006b, 0x0073} //从切片创建字符串 mystring2 := string(myslice2) //显示字符串 fmt.Println("String 2: ", mystring2) }

What does str mean in go language?

  • 如何查找字符串的长度?:在Golang字符串中,可以使用两个函数(一个是len(),另一个是RuneCountInString())来找到字符串的长度。UTF-8包提供了RuneCountInString()函数,该函数返回字符串中存在的符文总数。len()函数返回字符串的字节数。

//查找字符串的长度 package main import ( "fmt" "unicode/utf8" ) func main() { //创建和初始化字符串 //使用简写声明 mystr := "Welcome to nhooo ??????" //查找字符串的长度 //使用len()函数 length1 := len(mystr) //使用RuneCountInString()函数 length2 := utf8.RuneCountInString(mystr) //显示字符串的长度 fmt.Println("string:", mystr) fmt.Println("Length 1:", length1) fmt.Println("Length 2:", length2) }

What does str mean in go language?

【相关推荐:Go视频教程编程教学

The above is the detailed content of What does str mean in go language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn