假设我有一个代表有效 unicode 代码点的 int64 变量(或其他整数大小),并且我想在 Go 中将其转换为 rune ,我该怎么做?
在 C 语言中,我会使用类似这样的类型转换:
c = (char) i; // 7 bit ascii only
但是在 Go 中,类型断言是行不通的:
c, err = rune.( i)
建议?
最佳答案
你只需要 rune(i)
。转换是通过 type(x)
完成的。
类型断言有些不同。当您需要从不太具体的类型(如 interface{}
)转到更具体的类型时,您可以使用类型断言。此外,在编译时检查强制转换,类型断言在运行时发生。
这是使用类型断言的方法:
var (
x interface{}
y int
z string
)
x = 3
// x is now essentially boxed. Its type is interface{}, but it contains an int.
// This is somewhat analogous to the Object type in other languages
// (though not exactly).
y = x.(int) // succeeds
z = x.(string) // compiles, but fails at runtime
关于casting - 在 Go 中将 int 转换为 rune,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15983279/