2

As said in The Go Programming Language on page 55: "an EXPLICIT conversion is required to convert a value from one type to another", even if both of them have same underlying type. For example:

type myByte byte

func main() {
    var a byte
    var b myByte

    a = b       // Compile error: cannot use b (type myByte) as type byte in assignment
    a = byte(b) // OK
}

But for uint8 and byte, I'm surprised that the conversion is implicit:

func main() {
    var a byte
    var b uint8

    a = b // OK
    b = a // OK
}

So why?

2 Answers 2

9

byte is an alias for uint8 and is equivalent to uint8 in all ways.

From GoDoc:

type Byte

byte is an alias for uint8 and is equivalent to uint8 in all ways. It is used, by convention, to distinguish byte values from 8-bit unsigned integer values.

type byte byte // Really: type byte = uint8 (see golang.org/issue/21601)

https://golang.org/pkg/builtin/#byte

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

Comments

3

Earlier, on page 52 of The Go Programming Language, "the type byte is a synonym for uint8".


The Go Programming Language Specification

Numeric types

uint8       the set of all unsigned  8-bit integers (0 to 255)

byte        alias for uint8

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.