type Student struct{
Name string
No int
}
student:=Student{
Name:"Lily",
}
So,how can I know student's field "No" isn't assigned?
type Student struct{
Name string
No int
}
student:=Student{
Name:"Lily",
}
So,how can I know student's field "No" isn't assigned?
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.