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