Struct Field Reversion in Go
When attempting to modify a field in a struct within a Go program, you may encounter a scenario where the field seems to revert to its original value. This issue arises due to the way structures are passed by value in Go.
In your code, the MockConnector struct has two fields: last_command and value. The sendCommand method of MockConnector modifies these fields. However, when you call manager.sendMessage from the TVManager struct, you pass the connector instance as a value. This means that sendCommand receives a copy of the connector struct, rather than a reference to the original.
To resolve this issue, you need to use pointers to the structures involved. By passing a pointer to a structure, you pass a reference to the actual structure in memory. This allows you to modify the fields of the structure directly.
Corrected Code:
func (this *MockConnector) sendCommand(payload map[string]string) { fmt.Println("0", this) this.last_command = payload this.value = true fmt.Println("0", this) }
By modifying the sendCommand method to receive a pointer to the MockConnector struct, you now modify the actual connector instance instead of just a copy.
Receiver Name:
Additionally, it's considered best practice to avoid using this as the receiver name in Go struct methods. Instead, use a more descriptive name to indicate the type of receiver.
Consistent Method Set:
If one method in a struct requires a pointer receiver, it's recommended to make all methods in that struct use pointer receivers. This ensures consistency in the method set, regardless of whether the receiver is a value or a pointer.
By applying these recommendations, you can eliminate the issue of field values reverting in your Go program.
以上是為什麼我的 Go struct 欄位修改後會恢復為原始值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!