SpiderShrimp
SpiderShrimp

Reputation: 166

How to find struct's fields that aren'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?

Upvotes: 0

Views: 1191

Answers (5)

Prabesh P
Prabesh P

Reputation: 150

You to define the variable as a pointer variable

type Student struct{
    Name string
    No *int
}

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

In this case if you do

if student.No==nil{
    fmt.Println("Yes I'm unassigned")
}

it'll print

Yes I'm unassigned

We can use this technique while unmarshalling json, to find out whether a field is provided or not and while scanning a nullable value form database. To get the value back you have to use

*student.NO 

Upvotes: 2

nightfury1204
nightfury1204

Reputation: 4654

If you define No as integer, then if it's not assigned golang will set it to 0(default value) which is sometimes can be confusing based on the purpose you use it(for example, if 0 is a valid value for No).

If you really want to check whether Student.No is assigned or not. I think it's best to use Pointer.

type Student struct{
    Name string
    No *int
}

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

if student.No == nil {
    fmt.Println("student.No is not defined")
}

student2 := Student{
    Name: "Bob",
    No: func(i int) *int{ return &i}(5),
}

if student2.No != nil {
    fmt.Printf("student.No is %d\n", *student2.No)
}

Here is the code : https://play.golang.org/p/_lhbQcDA_eb

Upvotes: 4

nilsocket
nilsocket

Reputation: 1571

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.

Upvotes: 1

Andy Aldo
Andy Aldo

Reputation: 890

Every data type in Go has it's own "zero value". So, in No (number) case, it's 0. You can check if the value of No is 0.

More info here -> https://tour.golang.org/basics/12

Upvotes: 2

mbuechmann
mbuechmann

Reputation: 5770

This field will have the zero value for that data type. In this case a 0. Your check would look like this:

student.No == 0

This might seem a bit strange at first. But in this case a 0 as a number does not make sense as a valid student number.

Upvotes: 2

Related Questions