Char to Ascii int conversion in Go Language

huangapple go评论89阅读模式
英文:

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的别名,int32rune类型是相同的,你可以将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 = &#39;a&#39;
var i int = 100
if r &lt; i { // Compile-time error: invalid operation: r &lt; i (mismatched types rune and int)
	fmt.Println(&quot;less&quot;)
}

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 = &#39;a&#39;
var i int = 100
if int(r) &lt; i {
	fmt.Println(&quot;less&quot;)
}

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 = &#39;a&#39; // char
r &lt; 31

This worked for me

huangapple
  • 本文由 发表于 2016年9月15日 19:33:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/39510041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定