Go语言中从Char到Ascii int的转换

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?

2个回答

I found answer my self with below change

var r rune
r = 'a' // char
r < 31

This worked for me

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: Equivalent of python's ord(), chr() in go?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问