Home > database >  Numeric and String Operations in Golang
Numeric and String Operations in Golang

Time:12-24

https://go.dev/doc/effective_go

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
}

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

int(b[i]) - '0'

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?

CodePudding user response:

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 ('0' has default type rune) but are automatically coerced to comply with the context, so '0' ends up having the effective type int.

  •  Tags:  
  • go
  • Related