I haven"t been in contact with go for long. Today, I would like to discuss several questions about the literal quantity of structure, which can be regarded as a kind of record.
first question:
type Point struct{X,Y float64}
func pot(x,y float64) Point {
return Point{x,y}
}
func pt(x,y float64) *Point {
return &Point{x,y}
}
func main() {
pot(2,3).X = 4 // cannot assign to point(2, 3).X
pt(2,3).X = 4 //ok
}
reason for confusion: if the return is of * Point pointer type, the variable Point in the pt function will be assigned to the heap, and the Point scope will be expanded, so there is no problem in modifying the value.
but if Point is returned, why not change the value again?
my own idea : take a closer look at the code pot (2p3). X = 4 when performing the .X operation; the value of the Point type is still in the stack of the local function, and the value of the Point type returned from the pot function may be destroyed at some later time, if the .x is executed again; it is possible that the Point address has been reclaimed.
< hr >I look forward to your answer as follows:
1. It"s my own idea, so we can discuss
2. Since the above ideas are all conjectured based on the results, there may be errors, one-sided and lack of basis; if your ideas are well-founded, it would be better to have a reference source