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条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试