Why i can not assign int to byte

why it is impossible to do the following

rot13[i] = val + num

but it is ok to do that

rot13[i] = val + 22

if I am not mistaken 22 and num both are ints so i do not understand why this happen

func rotate(word []byte, num int) []byte {
var rot13 = make([]byte, len(word))
for i, val := range word {
	if val <= 109 {
		rot13[i] = val + num
	}else {
		rot13[i] = val - num
 return rot13

An int is a different type than a byte and Go does not do implicit conversions. You can do it yourself by saying byte(num), knowing that you will of course truncate the value as int is larger than byte.

The constant 22 is not an int - it’s an untyped constant. These can take on any numeric type depending on the context. In this case it will become a byte constant since it’s used in a byte context.

A numeric integer constant will default to the int type if there is no context (var foo = 22 // foo is now int), which is what you’re thinking of.

Here’s a deeper look at constants: https://blog.golang.org/constants


Killing it <3 :slight_smile:

Thank You

Calmh, Sunnykarira, guys thank you very much, you are really helping me to understand golang

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.