The golang function passes pointers and structures. How do you mask the details inside the function?

func main(){

    type ColorGroup struct {
        ID     int
        Name   string
        Colors []string
    }
    group := ColorGroup{
        ID:     1,
        Name:   "Reds",
        Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    }
//
    b, err := json.Marshal(&group)
//
    b, err := json.Marshal(group)
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
}

/ / the first way

b, err := json.Marshal(&group)

/ / the second way

b, err := json.Marshal(group)

the running results are: {"ID": 1, "Name": "Reds", "Colors": ["Crimson", "Red", "Ruby", "Maroon"]}

the b result is the same in both ways. Go is the value transfer, the first is to pass a copy of the pointer, and the second is to pass a copy of the structure.
so I think the question is how does the Marshall function mask the details of different parameters?

Why can both pass pointers and structures achieve the same effect?

the foundation of go is not good. Thank you for your advice.

Mar.20,2021

  • you can know what the input parameter is by reflection Kind .
  • The
  • structure pointer and the structure are no different from the Marshal function. The Elem function can access the structure Value that the pointer points to through the structure pointer.
Menu