英文:
Char to Ascii int conversion in Go Language
问题
我们正在进行从C# .Net到Go语言的项目迁移。我已经完成了大部分工作,但在一个地方卡住了。在C#中,我有一段代码:
(int)char < 31
我该如何在Go语言中编写这段代码?
英文:
we have a project migration happening from C# .Net to Go language. I have completed most part of it but i am stuck at one place. In c#, i have a code,
(int)char < 31
How can i write this in Go language?
答案1
得分: 2
在Go语言中,没有"char"类型,最接近的类型是rune
,它是int32
的别名。
作为int32
的别名,int32
和rune
类型是相同的,你可以将rune
视为int32
数字(因此可以进行比较、加减等操作)。
但是要知道,Go语言对类型要求非常严格,不能比较不同类型的值(在你的问题中,你将其与无类型整数常量进行比较是可以的)。例如,下面的代码会在编译时报错:
var r rune = 'a'
var i int = 100
if r < i { // 编译时错误:invalid operation: r < i (mismatched types rune and int)
fmt.Println("less")
}
如果你需要将rune
或其他整数类型的值转换为另一种整数类型(例如rune
转换为int
),你可以使用简单的类型转换,例如:
var r rune = 'a'
var i int = 100
if int(r) < i {
fmt.Println("less")
}
参考相关问题:https://stackoverflow.com/questions/29914662/equivalent-of-pythons-ord-chr-in-go
英文:
There is no "char" type in Go, the closest you can get is rune
which is an alias for int32
.
Being an alias of int32
means the types int32
and rune
are identical and you can treat a rune
like an int32
number (so you can compare it, add to it / subtract from it etc.).
But know that Go is strict about types, and you can't compare values of different types (in your answer you are comparing it with an untyped integer constant which is ok). For example the following code is a compile-time error:
var r rune = 'a'
var i int = 100
if r < i { // Compile-time error: invalid operation: r < i (mismatched types rune and int)
fmt.Println("less")
}
Should you need to convert a value of rune
or any other integer type to another integer type (e.g. rune
to int
), you can use simple type conversion, e.g..
var r rune = 'a'
var i int = 100
if int(r) < i {
fmt.Println("less")
}
See related question: https://stackoverflow.com/questions/29914662/equivalent-of-pythons-ord-chr-in-go
答案2
得分: -2
我发现了自己的答案,通过以下更改:
var r rune
r = 'a' // 字符
r < 31
这对我起作用了。
英文:
I found answer my self with below change
var r rune
r = 'a' // char
r < 31
This worked for me
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论