There is no way to do this but using a for-loop. In this case, it probably
means adding

for i, a := range p.Adr {
    if a.State == "" {
        a.State = "NY"
        p.Adr[i] = a
    }
}

before the last fmt.Printf.

On Mon, Oct 3, 2016 at 4:57 AM, Sarah Ahmed <[email protected]> wrote:

> Hello,
> I am trying to initialize the "State" to a default value "NY" of Address
> slice.
> The following code only sets the first element's State.
> I do not know how many element would be in my input.
> Is there any easy way to do it?
> Thanks in advance for your help.
>
> package main
>
> import (
>  "encoding/json"
>  "fmt"
>  "log"
> )
>
>
> type Address struct {
>  Street string `json:"Street"`
>  City   string `json:"City"`
>  State  string `json:"State"`
> }
>
>
> type Person struct {
>  Name string    `json:"Name"`
>  Adr  []Address `json:"Address"`
> }
>
>
> var p = &Person{Adr: []Address{Address{State: "NY"}}}
>
>
> func main() {
>  input:= "{\"Name\": \"User1\",\"Address\":[{\"Street\": \"Main
> St\",\"City\": \"City One\"},{\"Street\": \"Central St\",\"City\": \"City
> Two\"}]}"
>  err := json.Unmarshal([]byte(input), &p)
>  if err != nil {
>     log.Printf("Unmarshal error: ", err.Error())
>  }
>  fmt.Printf("%#v", p)
> }
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to