英文:
Golang func - return type
问题
这是我在“Hello world”之后的第一个Golang
程序。请查看以下代码块,它旨在执行基本算术和多类型返回演示。这只是一个假设的示例,用于学习Go func
。然而,在编译时我遇到了以下异常。根据异常,我假设对int8
操作数的操作返回int16/int32
作为返回类型,这在Go语言中是不正确的。
问题: 对于语言来说,假设int8
可以安全地赋值给int16
或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)
}
错误:
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
英文:
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
答案1
得分: 3
将其翻译为中文:
> 假设int8可以安全地赋值给int16或int32,这样是否安全?
是的,如果Go在赋值时进行隐式转换,那么是安全的。但是它不会这样做(只有在适用时才进行接口封装)。
有几个原因:
- 自动转换的概念不能推广到所有类型,而不引入类型层次结构的概念。而且,正如你所知,Go中的所有具体类型都是不变的。
- Go是"反魔法"的,按照这个精神,它不会执行你没有要求的操作(除了指针上的写屏障等情况)。
英文:
> 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
得分: 2
错误提示说你需要返回 int16 和 int32,你只需要像这样转换结果:
func Arithmetic(a, b int8) (int8, string, int16, int32) {
return a - b, "add", int16(a * b), int32(a / b)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论