DEV Community

Discussion on: It's Been Three Months Since My First Go LoC 🤓 🎓

Collapse
 
ladydascalie profile image
Benjamin Cable

how to distinguish between missing attributes and attributes with default values?

Use pointers!

Imagine the following:

type Person struct {
    Name *string
    Age  int
}

then try to unmarshal this: { "Age": 30 }

You will get this:

fmt.Printf("%#v\n", p)

> main.Person{Name:(*string)(nil), Age:30}

if a key is missing, it's a simple nil check away.

Another nice technique I like to use is as follows:

Declare an ok interface:

type ok interface {
    OK() error
}

Implement it on your type:

func (p *Person) OK() error {
    if p.Name == nil {
        return errors.New("missing field: name")
    }
    return nil
}

Then simply:

p.OK()

> 2009/11/10 23:00:00 missing field: name

You can see the full example in the go playground:

play.golang.org/p/P_88niVqOke