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:
以上是為什麼我的 Go 結構體欄位在方法呼叫後會恢復?的詳細內容。更多資訊請關注PHP中文網其他相關文章!