示例
// 字符串類型string的用法
package main
import (
"fmt"
"unsafe"
)
func main() {
// 字符串類型 str1
var str1 string = "上海 北京 12345 西安"
fmt.Printf("str1 的值為 %s, %v, %q, 類型為 %T, 占 %d 個字節\n", str1, str1, str1, str1, unsafe.Sizeof(str1)) // str1 的值為 上海 北京 12345 西安, 上海 北京 12345 西安, "上海 北京 12345 西安", 類型為 string, 占 16 個字節
var str2, str3 string = "hello ", "world"
fmt.Printf("str2 = %q, %v, %s, str3 = %q, %v, %s\n", str2, str2, str2, str3, str3, str3) // str2 = "hello ", hello , hello , str3 = "world", world, world
// 錯誤:cannot assign to str2[1]
// go中的字符串是不可變的,一旦被賦值,不能再修改
// str2[1] = 'k'
// fmt.Printf("str2 = %v\n", str2)
// 雙引號會識別轉義字符
// 中文字符串
str4 := "你好\000北京\t上海濟南武漢\007天津\x7f"
fmt.Printf("str4 = %v\n", str4) // str4 = 你好北京 上海濟南武漢天津
fmt.Printf("str4 = %s\n", str4) // str4 = 你好北京 上海濟南武漢天津
// %v和%s一起格式化字符串時,輸出的結果不一樣
fmt.Printf("str4 = %v, %s\n", str4, str4) // str4 = 你好北京 上海濟南武漢天., 你好北京 上海濟南武漢天津
// 英文字符串
str5 := "hello\000world\tgood\007yellow\x7f"
fmt.Printf("str5 = %v\n", str5) // str5 = helloworld goodyellow
fmt.Printf("str5 = %s\n", str5) // str5 = helloworld goodyellow
// %v和%s一起格式化字符串時,輸出的結果不一樣
fmt.Printf("str5 = %v, %s\n", str5, str5) // str5 = helloworld goodyello, helloworld goodyellow
// 反引號,以字符串的原生形式輸出,包括換行和特殊字符
// 下面用反引號原樣輸出一段示例代碼
var str6 = `
// bool布爾類型的用法
package main
import (
"fmt"
"unsafe"
)
func main() {
// bool類型
b1 := false
fmt.Printf("b1的值為 %t, 類型為 %T, 占 %d 個字節\n", b1, b1, unsafe.Sizeof(b1)) // b1的值為 false, 類型為 bool, 占 1 個字節
// b1 = 1 會報錯: cannot use 1 (type int) as type bool in assignment
// 因為b1是bool類型,只能取值true或者false
// 不可以用0或者非0的整數替代false或者true,這點與C語言不同
// n1 := 1
// 錯誤:non-bool n1 (type int) used as if condition
// if n1 {
// fmt.Printf("n1 = %d\n", n1)
// }
// 錯誤:cannot use 0 (type int) as type bool in assignment
// var b2 bool = 0
// fmt.Printf("b2 = %t\n", b2)
}
`
fmt.Printf("\t示例代碼: \n%v\n", str6)
// 以上代碼會輸出:
//
// 示例代碼:
// bool布爾類型的用法
// package main
// import (
// "fmt"
// "unsafe"
// )
// func main() {
// // bool類型
// b1 := false
// fmt.Printf("b1的值為 %t, 類型為 %T, 占 %d 個字節\n", b1, b1, unsafe.Sizeof(b1)) // b1的值為 false, 類型為 bool, 占 1 個字節
// // b1 = 1 會報錯: cannot use 1 (type int) as type bool in assignment
// // 因為b1是bool類型,只能取值true或者false
// // 不可以用0或者非0的整數替代false或者true,這點與C語言不同
// // n1 := 1
// // 錯誤:non-bool n1 (type int) used as if condition
// // if n1 {
// // fmt.Printf("n1 = %d\n", n1)
// // }
// // 錯誤:cannot use 0 (type int) as type bool in assignment
// // var b2 bool = 0
// // fmt.Printf("b2 = %t\n", b2)
// }
// 用加號 '+' 進行拼接
str7, str8, str9 := "你好", " 中國 ", "北京"
// 加號兩邊必須都是字符串才可以拼接
newStr1 := str7 + str8 + str9
fmt.Printf("拼接之后的新串為 %q, %v\n", newStr1, newStr1) // 拼接之后的新串為 "你好 中國 北京", 你好 中國 北京
// 字符串過長時用 '+' 進行分行,然后拼接
// 加號必須放在分行的最右邊
var str10 string = "劍閣崢嶸而崔嵬,一夫當關,萬夫莫開。" +
"所守或匪親,化為狼與豺。朝避猛虎,夕避長蛇;磨牙吮血," +
"殺人如麻。錦城雖雲樂,不如早還家。蜀道之難,難於上青天," +
"側身西望長咨嗟!"
fmt.Printf("str10的內容為:%v\n", str10) // str10的內容為:劍閣崢嶸而崔嵬,一夫當關,萬夫莫開。所守或匪親,化為狼與豺。朝避猛虎,夕避長蛇;磨牙吮血,殺人如麻。錦城雖雲樂,不如早還家。蜀道之難,難於上青天,側身西望長咨嗟!
}
查看源代碼
總結
