Go语言程序使字符串不可变
在Go语言中,字符串默认是不可变的。一旦创建,字符串就不能被修改。如果尝试更改字符串的值,将会出现编译时错误。因此,无需添加任何额外的逻辑来使其不可变。让我们看看它是如何执行的。在这里,我们将学习使用Go编程使字符串不可变的不同技术。
算法
步骤1 - 创建一个`main`包,并在程序中声明`fmt`(格式化包),其中`main`生成可执行代码,`fmt`帮助格式化输入和输出。
步骤2 - 创建一个`main`函数,并在该函数中用某个值初始化一个字符串。
步骤3 - 更改字符串值的引用,并使用`fmt.Println()`函数将其打印到屏幕上,其中`ln`表示换行。
步骤4 - 在这里,我们不能更改原始字符串,但可以修改其引用。
示例1
在这个例子中,我们将看到如何使用字符串字面量使字符串不可变。输出将是使用`fmt.Println()`(Go语言中的打印函数)打印到屏幕上的字符串值。
package main
import "fmt"
func main() {
// Create an immutable string
var str_val = "Hello, World!"
str_val = "Cannot change this string" // string reference is given here
fmt.Println("The string presented here is:")
fmt.Println(str_val) //print the string value
}
输出
The string presented here is: Cannot change this string
示例2
Go语言程序使用`bytes.Buffer`包使字符串不可变的示例。
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
buffer.WriteString("Hello, World!") //add string to the buffer
val := buffer.String() //store the buffer string in val
fmt.Println("The string presented here is:")
fmt.Println(val) //print string on the console
buffer.WriteString("Cannot change this string")
}
输出
The string presented here is: Hello, World!
示例3
在这个例子中,我们将看到如何修改字符串的引用,而不是原始字符串。我们将连接字符串并使用Go语言中的打印语句将其打印到屏幕上。
package main
import "fmt"
func main() {
str := "hello" // create string
fmt.Println("The original string is:", str)
str = str + " world" //concatenation
fmt.Println("The reference string in which new string concatenated is:")
fmt.Println(str) // prints "hello world"
// str is still "hello"
}
输出
The original string is: hello The reference string in which new string concatenated is: hello world
示例4
在这个例子中,我们将看到如何使用字节切片然后将其转换回字符串来使字符串不可变。输出字符串将打印到屏幕上。
package main
import "fmt"
func main() {
byte_val := []byte("hello") //create byte slice
byte_val[0] = 'E' //modify 0th value
str := string(byte_val) //cast it to string
fmt.Println("The immutability of string is presented as:")
fmt.Println(str) // print the string on console
}
输出
The immutability of string is presented as: Eello
结论
我们使用四个示例执行了使字符串不可变的程序。在第一个示例中,我们使用字符串字面量创建字符串,然后进行修改。在第二个示例中,我们使用`bytes.Buffer`包使字符串不可变。在第三个示例中,我们连接了新值,在第四个示例中,我们使用了字节切片并将其转换为字符串。因此,程序成功执行。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP