dop83362 2016-10-25 22:00
浏览 270
已采纳

Golang函数-返回类型

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条回答 默认 最新

  • duanjiao5082 2016-10-26 13:25
    关注

    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).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,