Home > Backend Development > Golang > Why Does My Go Struct Field Revert to Its Original Value When Modified?

Why Does My Go Struct Field Revert to Its Original Value When Modified?

Linda Hamilton
Release: 2024-11-15 15:45:02
Original
863 people have browsed it

Why Does My Go Struct Field Revert to Its Original Value When Modified?

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)
}
Copy after login

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.

The above is the detailed content of Why Does My Go Struct Field Revert to Its Original Value When Modified?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template