1
votes

This is my first Golang program after 'Hello world'. Please find following code block which aims to perform basic arithmetic and multiple type return demo. This is just a hypothetical sample to learn Go func. However, I am getting following exception on compilation. From exception, i assume, operations on int8 operand return int16/int32 as return type and which is not correct as per go.

Question: Isn't it safe for language to assume int8 is safely assignable to int16 or int32

package main
import (
    "fmt"
)
func Arithmetic(a,b int8) (int8,string,int16,int32){
    return a-b, "add",a*b,a/b
}
func main() {
    a,b,c,d :=Arithmetic(5,10)
    fmt.Println(a,b,c,d)
}

Error:

C:/Go\bin\go.exe run C:/GoWorkspace/src/tlesource/ff.go
# command-line-arguments
.\ff.go:15: cannot use a * b (type int8) as type int16 in return argument
.\ff.go:15: cannot use a / b (type int8) as type int32 in return argument

Process finished with exit code 2
2
You can't assign int8 to int16 or int32, but you can safely convert them. - JimB
You have to explicitly cast it using int16(), etc - Shmulik Klein
@JimB, Thank you for your comment. I might be wrong, however, Safe assignment and conversion is different. - Sreejith Nair
@ShmulikKlein, Thanks for your comment. Casting might be a valid if we try to down cast. But this is a case of up casting. So, I assume, this should be an easy task for compiler with out any helping hands. - Sreejith Nair
@Nair: What exactly are you asking? You cannot assign an int8 to an int16/int32/etc. Just because it's "safe" doesn't mean they are assignable; they are different types. golang.org/ref/spec#Assignability - JimB

2 Answers

3
votes

Is it it safe for language to assume int8 is safely assignable to int16 or int32

Yes, It would be, if Go did implicit conversions on assignment. But it does not (only interface-wrapping when applicable).

There are several reasons:

  • The concept of automatic conversion cannot be generalized to all types without introducing the concept of a type hierarchy. And, as you know, all concrete types in Go are invariant.
  • Go is "anti-magic" and in this spirit it doesn't do stuff you did not request it to do (except e.g. write-barriers on pointers).
2
votes

The error says that you have to return int16 and int32, all you have to do is convert the result like this:

func Arithmetic(a, b int8) (int8, string, int16, int32) {
    return a - b, "add", int16(a * b), int32(a / b)
}