结构方法是设置字段,但是没有被“保存”吗? [重复]

This question already has an answer here:

I know the title is confusing, and it is for me as well, as it says I have packets that decode binary data from byte buffers, each data value is set to a specific field of a struct. First I make a new struct of that type and call the "Decode" method:

text := packets.NewTextPacket()
text.Buffer = bytes
text.DecodeHeader()
text.Decode()

The problem is that I specifically call the method called "Decode", here you can see what it does:

func (pk TextPacket) Decode() {
    pk.TextType = pk.GetByte()
    pk.Translation = pk.GetBool()

    switch pk.TextType {
    case Raw, Tip, System:
        pk.Message = pk.GetString()
        break
    case Chat, Whisper, Announcement:
        pk.Source = pk.GetString()
        pk.SourceThirdParty = pk.GetString()
        pk.SourcePlatform = pk.GetVarInt()
        pk.Message = pk.GetString()
        break
    case Translation, Popup, JukeboxPopup:
        pk.Message = pk.GetString()
        c := pk.GetUnsignedVarInt()
        for i := uint32(0); i < c; i++ {
            pk.Params = append(pk.Params, pk.GetString())
        }
        break
    }

    pk.Xuid = pk.GetString()
    pk.PlatformChatId = pk.GetString()
}

When I print pk.Message inside func (pk TextPacket) Decode() it shows the correct string, but printing it after text.Decode() as text.Message, it shows the default value that is set when the struct is first made, which is an empty string, same goes for all the other fields such as text.TextType, etc.

</div>

You're using a value receiver, so the method modifies a copy of the object. Try changing to a pointer receiver: pk *TextPacket

See A Tour of Go for a nice concise explanation: https://tour.golang.org/methods/4