About the confusion caused by type conversion in golang

102 views
Skip to first unread message

Barry Li

unread,
Jan 27, 2021, 8:13:31 PM1/27/21
to golang-nuts
Some doubts about type conversion in go.
In the following code, why can it be executed normally after passing the variable?
The code is an error during the compilation phase.

// The following two lines of code can be executed normally
    x := uint64(256)
    fmt.Println(byte(uint64(x))) // normal execution

// The following code cannot be executed normally
    fmt.Println(byte(uint64(256))) // constant 256 overflows byte

Can anyone help me answer it?

Ian Lance Taylor

unread,
Jan 27, 2021, 8:39:22 PM1/27/21
to Barry Li, golang-nuts
In Go, arithmetic on constant values follows different rules than
arithmetic on variable values. For example, as you've seen, an
out-of-range conversion is a compilation error for constants but a run
time error for variables. The same is true of division by zero. See
https://golang.org/ref/spec#Constant_expressions.

Ian

Arunkumar Gudelli

unread,
Jan 28, 2021, 12:45:24 AM1/28/21
to Barry Li, golang-nuts
256 considered as `constant`. (untyped)
So when we try to convert to byte (which has a range from 0 to 255), it will throw the overflow error.

Where `x := uint64(256)` we are giving a type to constant uint64. 

y := byte(256) // Same error

so byte(uint64) will be zero without any errors.

regards,
Arun Gudelli

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/401197ca-1cdc-45e8-9135-bafe0a300e21n%40googlegroups.com.

Rob Pike

unread,
Jan 28, 2021, 1:46:29 AM1/28/21
to Arunkumar Gudelli, Barry Li, golang-nuts
This topic is well explained in the blog post at blog.golang.org/constants, if I do say so myself.

-rob


Reply all
Reply to author
Forward
0 new messages