Go語言的 string(字串)連接int(整數)的方式如下。
Go語言string不能直接用+連接int,例如下面寫法會報錯。
fmt.Println("John is " + 22 + " years old.") // invalid operation: "John is " + 22 (mismatched types untyped string and untyped int)
必須用內建標準函式庫strconv包的Itoa(i int) string將int轉為string後才能用+連接。
fmt.Println("John is " + strconv.Itoa(22) + " years old.")
或是用fmt.Printf()字串格式化處理%s對字串,%d對數字。
fmt.Printf("%s%d%s", "John is ", 22, " years old.\n")
或是用fmt.Sprint()連接。
message := fmt.Sprint("John is ", 22, " years old.\n")
fmt.Printf(message)
對寫習慣Java的我覺得真不方便,通常在其他語言都可以直接用+串接整數。
Java
System.out.println("John is " + 22 + " years old.");
JavaScript
console.log('John is ' + 22 + ' years old.')
C#
Console.WriteLine("John is " + 22 + " years old.");
沒有留言:
張貼留言