← 中文资源

简体中文版本

Itoa 与 string 码点转换之别

strconv.Itoa 输出整数的十进制数字,而 string(n) 把整数当作 Unicode 码点做转换:两者几乎从来不可互换,负数还会退化成替换符。

阅读英文原文

实现说明

Itoa 与 string 码点转换之别的核心是函数 main。

使用要点

  • 跑完文件,输出里会留下标记——digits:、code points:、emoji:。

常见问题

运行「Itoa 与 string 码点转换之别」会打印什么?

运行文件本身,digits:、code points:、emoji: 这些前缀各对应一段演示逻辑。

核心语句

package main

代码示例

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// strconv.Itoa renders decimal digits versus string(n), which treats the integer as a rune code point
	fmt.Println("digits:", strconv.Itoa(65), strconv.Itoa(300))
	fmt.Println("code points:", string(65), string(300))

	// code points are how unicode lands in strings
	fmt.Println("emoji:", string(rune(0x1F600)))

	// negative or out-of-range values collapse to the replacement rune
	fmt.Println("negative rune:", string(rune(-1)))

	// the vet warning exists because string(65) is almost never what you meant
	fmt.Println("round trip:", strconv.Itoa('A'), string(rune('A')))
}