dongshi1880 2018-11-02 07:02
浏览 60
已采纳

如何查找未在golang中分配的struct字段?

type Student struct{
    Name string
    No int
}

student:=Student{
    Name:"Lily",
}

So,how can I know student's field "No" isn't assigned?

  • 写回答

5条回答 默认 最新

  • dongtaoxue4674 2018-11-02 07:46
    关注

    There is no other way to check if some value is set or not without manually comparing each and every field of a struct.

    That's the reason why, in stdlib many packages have methods New....

    For example bufio.NewWriter(), where the author of the package takes care of initializing the struct with some sane default values according to one's own use case.

    // NewStudent returns new Student instance
    func NewStudent() *Student {
        return &Student{Name: "defaultName", No: 7}
    }
    

    Even though Student type is exported, your package users are supposed to use New... to use any struct.

    There is also another way one can manage this problem, but it maybe too much of stretch for many programs, but you can read about them here and here.

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

报告相同问题?