doufang8282 2015-03-20 06:28
浏览 2541
已采纳

如何动态清除golang中类型结构实例的值?

Is it possible with golang to make a method that dynamically clears the values of a instance of a struct? btw Im new to golang.

type A struct {
    Name string
    Level int
}

type B struct {
    Skill string
}

func main() {
    a := A{"Momo", 1}
    b := B{"Starfall"}

    // outputs
    // {"Momo", 1}
    // {"Starfall"}

    clear(a)
    clear(b)

    // outputs
    // { , 0}
    // { }
}

func clear(v interface{}) {
    // some code
}
  • 写回答

4条回答 默认 最新

  • dongyun9120 2015-03-20 07:06
    关注

    You can't modify the original values without passing a pointer to them.

    It's much easier and more clear to simply assign a new zero value in your code. If your types are more complex, you can replace the values with a constructor, or provide Reset() methods for your types with a pointer receiver.

    If you really want to see how to do it via reflection your clear function could look like: http://play.golang.org/p/g0zIzQA06b

    func clear(v interface{}) {
        p := reflect.ValueOf(v).Elem()
        p.Set(reflect.Zero(p.Type()))
    }
    

    (This will panic if you pass in a non-pointer value)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部