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 https://golangtutorial.dev/ On Thu, Jan 28, 2021 at 6:43 AM Barry Li <barrya...@gmail.com> wrote: > 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? > > -- > 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+unsubscr...@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 > <https://groups.google.com/d/msgid/golang-nuts/401197ca-1cdc-45e8-9135-bafe0a300e21n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- 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+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOOGzbXe84WeaN2rE7POow5gs_T5JikJfH9Vh8_EruEK_C3bKw%40mail.gmail.com.