了解命名返回类型的内存分配

In the following code sample, can I assume that I don't need to allocate the returned value? Will the compiler always allocate any function's named returned value?

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
", MakePoint(1, 2))
}

Also, why do I need to add the return statement at the end of the function? Is this a bug with the compiler?

If I decide to return a pointer:

func MakePoint(x, y int) (pt *Point) {

The code will compile but I am getting a runtime error! Why is the compiler letting me believe an allocation with a statement such as pt = new(Point) is not needed? Is this another bug with the compiler? Clearly, I am missing something crucial about memory allocation in Go.

Will the compiler always allocate any function's named returned value?

Yes, absolutely.

Also, why do I need to add the return statement at the end of the function? Is this a bug with the compiler?

Because function which return a value must end in a return statement. That's what the language spec requires and the compiler enforces.

Why is the compiler letting me believe an allocation with a statement such as pt = new(Point) is not needed?

The compiler allocates space for the pointer (that's what you return) but he cannot know where the memory for the actual Point shall be. That's your job.

Is this another bug with the compiler?

No. Such stuff is fundamental. The chances you discover such a bug in such obvious code is basically zero.

In the following code sample, can I assume that I don't need to allocate the returned value? Will the compiler always allocate any function's named returned value?

I assume by allocate you don't mean assigning like this:

a := func(1,2)

In this case, compiler will assign whatever comes out of func to a.

But I think you mean allocating function result variables.

1. Yes, in this case you don't need to allocate as this is just a value.

2. Nope. It depends whether value is a pointer or a concrete type. In concrete type, you don't need to allocate in any case.

Also, why do I need to add the return statement at the end of the function? Is this a bug with the compiler?

Now to return part, according to standard:

If the function's signature declares result parameters, the function body's statement list must end in a terminating statement.

And this result can be named or not.

The code will compile but I am getting a runtime error! Why is the compiler letting me believe an allocation with a statement such as pt = new(Point) is not needed? Is this another bug with the compiler?

It isn't a bug. It's happening because compiler doesn't care about which concrete type a pointer's point. Its create a pointer with zero value of nil. You need to take care of it. Otherwise, you get nil pointer dereference as you still haven't pointed it to any concrete type.