douzhenao6515 2018-06-21 01:41
浏览 59
已采纳

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

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>
  • 写回答

1条回答 默认 最新

  • duannaiying9662 2018-06-21 02:06
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路