DEV Community

HM
HM

Posted on

2 2

Default value in a struct

#go
/*
    set default values for a struct being Unmarshaled from json
*/
package main

import (
    "encoding/json"
    "fmt"
)

type Out struct {
    A string `json:"a"`
    B string `json:"b"`
    C string `json:"c"`
    D int    `json:"d"`
}

func main() {
    in := []byte(`{"a":"1"}`)
    out := Out{
        A: "defaultA",
        B: "defaultC",
        C: "defaultD",
        D: 99,
    }
    json.Unmarshal(in, &out)
    fmt.Printf("%+v\n ", out)
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay