casting - 在 Go 中将 int 转换为 rune

标签 casting go type-conversion rune

假设我有一个代表有效 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/

相关文章:

c# - 在 C# 和 VB.NET 中自动转换为字符串

c - 如何手动(按位)执行(float)x?

java - 将 Java 对象转换为 Java Map<String,Object>

arrays - 将 json 文件编码到 map 中

json - Golang 结构不会编码为 JSON

c++ - 在 C++ 中进行类型转换的简短而优雅的方法?

c++ - 如何使用 std::map 从模板中获取数据类型

objective-c - 为什么我需要将 self 转换为 id?

postgresql - Golang 测试中可重用的组件和固定装置

swift - 在 Apples Swift 3 beta 6 中使用 withMemoryRebound