I have a struct, say:
type sample struct{
data []float64
}
Now, I declare a method:
func (s sample) Get() *[]float64{
return &s.data
}
I am trying to append to this slice via the pointer I got via Get()
func main(){
example := sample{[]float64{1,2,3}}
//Here I will append:
pointerToArray := example.Get()
*pointerToArray = append(*pointerToArray, 4)
fmt.Println(example.Get()) // still shows only &{1,2,3}
}
I have a general idea of why this is happening: The function Get is returning the address of its local scope, and I have fixed it by change the struct itself to
type sample struct{
data *[]float64
}
for which the code returns the expected &{1,2,3,4}
Now, for my question: Is there anyway to get the real pointer to the field in the struct through a getter method without using a pointer field directly in the struct?
The problem is that you've defined the Get
method with a struct receiver, rather than on a pointer. That means when you return &s.data
you get the address of the field of receiver, rather than from the original struct. You can fix this simply by using a pointer receiver:
func (s *sample) Get() *[]float64{
return &s.data
}
Here's a complete runnable example ( https://play.golang.org/p/AIj8QOYfx85 )
package main
import "fmt"
type sample struct {
data []float64
}
func (s *sample) Get() *[]float64 {
return &s.data
}
func main() {
example := sample{[]float64{1, 2, 3}}
p := example.Get()
*p = append(*p, 4)
fmt.Println(example.Get())
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.