在Golang中的数字和字符串操作

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

Numeric and String Operations in Golang

问题

以下是翻译好的内容:

func nextInt(b []byte, i int) (int, int) {
    for ; i < len(b) && !isDigit(b[i]); i++ {
    }
    x := 0
    for ; i < len(b) && isDigit(b[i]); i++ {
        x = x*10 + int(b[i]) - '0'
    }
    return x, i
}

我不知道上述代码中以下部分是什么操作。

int(b[i]) - '0'

这是一个数字和字符串相减,但是这是什么样的计算呢?
在官方文档或类似的地方可以找到吗?

英文:

https://go.dev/doc/effective_go

func nextInt(b []byte, i int) (int, int) {
    for ; i &lt; len(b) &amp;&amp; !isDigit(b[i]); i++ {
    }
    x := 0
    for ; i &lt; len(b) &amp;&amp; isDigit(b[i]); i++ {
        x = x*10 + int(b[i]) - &#39;0&#39;
    }
    return x, i
}

I don't know what kind of operation the following part of the above code is.

int(b[i]) - &#39;0&#39;

It's a subtraction of a number and a string, but what kind of calculation is it?
Where can I find it in the official documentation or something similar?

答案1

得分: 1

在Go语言中,单引号括起来的字面量的类型是runeruneint32的别名,但更重要的是,它表示字符的Unicode码点值。

你可以在这篇博文"Go中的字符串、字节、符文和字符"中了解一些背景知识。

b []byte(字节切片)被nextInt函数解释为一系列Unicode字符的UTF-8表示。幸运的是,对于ASCII数字,你只需要8位(一个byte)来表示字符,而不是一个完整的rune

数字0到9的ASCII值是Unicode码点集的一个子集,它们直接相邻。因此,如果你取一个数字的ASCII值,并从ASCII值为零的数字的ASCII值中减去它,你就得到了该数字的数值。

这就是这里发生的事情。

一个小细节是,在Go中,通常你只能从彼此完全相同类型的值中相减。而在这种情况下,你不能从一个rune中减去一个int。但是在Go中,常量是无类型的。它们只有一个默认类型('0'的默认类型是rune),但会自动强制转换以符合上下文,所以'0'最终具有有效类型int

英文:

The type of a single-quoted literal in Go is rune.
rune is an alias for int32, but more importantly, it represents the Unicode codepoint value for a character.

You can read some background in this blog post on "Strings, bytes, runes and characters in Go"

The b []byte (slice of bytes) is interpreted by the nextInt function as a the UTF-8 representation of a series of Unicode characters. Luckily, for ASCII numeric digits, you only need 8 bits (a byte) to represent the character, not a full rune.

The ASCII value, which is a subset of the Unicode codepoint set, of the digits 0 to 9 are following each directly. So if you take the ASCII value of a digit, and you subtract the ASCII value of the digit zero from it, you end up with the numeric value of the digit.

That's what is happening here.

A minor detail is that in Go, normally you can only subtract values of exactly the same type from each other. And in this case, you wouldn't be able to subtract a rune from an int. But constants in Go are untyped. They only have a default type (&#39;0&#39; has default type rune) but are automatically coerced to comply with the context, so &#39;0&#39; ends up having the effective type int.

huangapple
  • 本文由 发表于 2022年12月22日 14:39:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/74884939.html
匿名

发表评论

匿名网友

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

确定