In Go, a pointer receiver function allows you to modify the value of the receiver object. However, understanding how pointers work in Go is crucial for successful implementation.
When trying to modify the value of a simple type through a pointer receiver method, one might encounter situations where the changes do not persist outside the method. This is because all method arguments, including the receiver, are copied locally within the method's execution.
In the example provided:
func (fi *FooInt) FromString(i string) { num, _ := strconv.Atoi(i) tmp := FooInt(num) fi = &tmp }
The fi pointer argument is a copy of the original fi pointer in main. Therefore, changes made to the copied fi pointer within the FromString method only affect the local copy, not the original pointer.
To resolve this, there are a few options:
Create a return statement that assigns the updated pointer to the receiver, and then reassign the returned pointer in main.
// Return the updated pointer and reassign it in main func (fi *FooInt) FromString(i string) *FooInt { num, _ := strconv.Atoi(i) tmp := FooInt(num) return &tmp } // Reassign the updated pointer in main func main() { var fi *FooInt fi = fi.FromString("5") fmt.Printf("%v %v\n", fi, *fi) // Outputs: 0xc0000b4020 5 }
Pass a non-nil pointer of the target type as an argument to the method.
// Pass a non-nil pointer as an argument func (fi *FooInt) FromString(i string, p **FooInt) { num, _ := strconv.Atoi(i) tmp := FooInt(num) *p = &tmp } // Create a non-nil pointer and pass it to the method in main func main() { var fi *FooInt fi.FromString("5", &fi) fmt.Printf("%v %v\n", fi, *fi) // Outputs: 0xc0000b4020 5 }
Check if the receiver pointer is non-nil before modifying it.
// Check if the receiver is non-nil before modifying func (fi *FooInt) FromString(i string) { if fi == nil { return } num, _ := strconv.Atoi(i) *fi = FooInt(num) } // Create a non-nil receiver in main func main() { fi := new(FooInt) fi.FromString("5") fmt.Printf("%v %v\n", fi, *fi) // Outputs: 0xc0000b4020 5 }
以上是Go中如何透過指標接收器方法修改值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!