英文:
Cast/convert int to rune in Go
问题
假设我有一个表示有效Unicode码点的int64变量(或其他整数大小),我想将其转换为Go中的rune,我该怎么做?
在C中,我会使用类型转换,类似于:
c = (char) i; // 仅限7位ASCII
但在Go中,类型断言不起作用:
c, err = rune.( i)
有什么建议吗?
英文:
Assuming I have an int64 variable (or other integer size) representing a valid unicode code-point, and I want to convert it into a rune in Go, what do I do?
In C I would have used a type cast something like:
c = (char) i; // 7 bit ascii only
But in Go, a type assertion won't work:
c, err = rune.( i)
Suggestions?
答案1
得分: 21
你只需要 rune(i)
。类型转换通过 type(x)
来完成。
类型断言是另一回事。当你需要从一个不太具体的类型(比如 interface{}
)转换为一个更具体的类型时,你会使用类型断言。此外,类型转换在编译时进行检查,而类型断言在运行时发生。
以下是如何使用类型断言的示例:
var (
x interface{}
y int
z string
)
x = 3
// x 现在本质上是被封装的。它的类型是 interface{},但它包含一个 int。
// 这在某种程度上类似于其他语言中的 Object 类型
// (尽管不完全相同)。
y = x.(int) // 成功
z = x.(string) // 编译通过,但在运行时失败
英文:
You just want rune(i)
. Casting is done via type(x)
.
Type assertions are something different. You use a type assertion when you need to go from a less specific type (like interface{}
) to a more specific one. Additionally, a cast is checked at compile time, where type assertions happen at runtime.
Here's how you use a type assertion:
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
答案2
得分: 3
在Go语言中,你想要进行一次转换。
转换是形式为
T(x)
的表达式,其中T
是一个类型,x
是一个可以转换为类型T
的表达式。转换 = 类型 "(" 表达式 ")" .
一个非常量值
x
可以在以下任何情况下转换为类型T
:
x
可以赋值给T
。x
的类型和T
具有相同的基础类型。x
的类型和T
是未命名指针类型,并且它们的指针基础类型具有相同的基础类型。x
的类型和T
都是整数或浮点数类型。x
的类型和T
都是复数类型。x
是一个整数或具有类型[]byte
或[]rune
,而T
是一个字符串类型。x
是一个字符串,而T
是[]byte
或[]rune
。
你想要将类型为int
、int32
或int64
的x
转换为类型为rune
的T
,其中rune
是int32
类型的别名。x
的类型和T
都是整数类型。
因此,T(x)
是允许的,并且可以写为rune(x)
,对于你的例子,c = rune(i)
。
英文:
In Go, you want to do a conversion.
> Conversions
>
> Conversions are expressions of the form T(x)
where T
is a type and
> x
is an expression that can be converted to type T
.
>
> Conversion = Type "(" Expression ")" .
>
> A non-constant value x
can be converted to type T
in any of these
> cases:
>
> * x
is assignable to T
.
> * x
's type and T
have identical underlying types.
> * x
's type and T
are unnamed pointer types and their pointer base types have identical underlying types.
> * x
's type and T
are both integer or floating point types.
> * x
's type and T
are both complex types.
> * x
is an integer or has type []byte
or []rune
and T
is a string type.
> * x
is a string and T
is []byte
or []rune
.
You want to convert x
, of type int
, int32
, or int64
, to T
of type rune
, an alias for type int32
. x
's type and T
are both integer types.
Therefore, T(x)
is allowed and is written rune(x)
, for your example, c = rune(i)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论