Struct Field Reverting
In the provided Go code, a strange behavior is observed where a struct field changes within a method but reverts to its original value when checked afterward. This issue stems from the fact that the struct is being passed by value instead of by pointer.
Explanation:
In the sendMessage method of the TVManager struct, a method sendCommand of a connector struct is called with a value of the TVManager struct. When a struct is passed by value, a copy of the struct is created and passed instead of a reference to the original struct.
In the sendCommand method of the MockConnector struct, the fields of the connector struct (e.g., last_command, value) are modified. However, since the connector is being passed by value, the modifications are only applied to the copy of the struct, not the original one.
To resolve this issue, the connector struct in the sendCommand method should be passed by pointer instead of by value. This allows the method to modify the original connector struct, rather than a copy.
Solution:
Replace:
func (this MockConnector) sendCommand(payload map[string]string)
With:
func (this *MockConnector) sendCommand(payload map[string]string)
Additional Considerations:
The above is the detailed content of Why Does My Go Struct Field Revert After a Method Call?. For more information, please follow other related articles on the PHP Chinese website!