在下面的代码示例中,我可以假设我不需要分配返回值吗?编译器是否总是分配任何函数的命名返回值?
package main
import "fmt"
type Point struct {
X, Y int
}
func MakePoint(x, y int) (pt Point) {
pt.X = x
pt.Y = y
return
}
func main() {
fmt.Printf("%v\n", MakePoint(1, 2))
}
另外,为什么我需要在函数末尾添加return
语句?这是编译器的错误吗?
如果我决定返回一个指针:
func MakePoint(x, y int) (pt *Point) {
代码可以编译,但出现运行时错误!为什么编译器让我相信不需要使用诸如 pt = new(Point)
之类的语句进行分配?这是编译器的另一个错误吗?显然,我遗漏了一些关于 Go 内存分配的重要信息。
最佳答案
Will the compiler always allocate any function's named returned value?
是的,绝对。
Also, why do I need to add the return statement at the end of the function? Is this a bug with the compiler?
因为返回值的函数必须以 return 语句结束。这是语言规范所要求的,也是编译器强制执行的。
Why is the compiler letting me believe an allocation with a statement such as pt = new(Point) is not needed?
编译器为指针分配空间(即您返回的内容),但他不知道实际 Point 的内存在哪里。那是你的工作。
Is this another bug with the compiler?
没有。这些东西是基本的。在如此明显的代码中发现此类错误的机会基本上为零。
关于go - 了解命名返回类型的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37517426/