0

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?

2
  • It's a subtraction of a number of type int and a rune - a literal in single quotes has the type rune in Go. It is the unicode codepoint value of the digit zero: compart.com/en/unicode/U+0030 Commented Dec 22, 2022 at 7:09
  • The single quotes in Go are not quotes for strings. The language spec ("official documentation") is available under go.dev/ref/spec . Commented Dec 22, 2022 at 7:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.