lundi 23 juillet 2018

Why Go reflect NumField() is only available on the type?

I have the following Go code (play.golang.org):

package main

import (
    "reflect"
    "fmt"
)

type User struct {
    name string
    email string
}

func main() {   
    uS := User{}
    uSt := reflect.TypeOf(uS)   

    fmt.Println( uSt )
    fmt.Println( uSt.NumField() )
    // fmt.Println( uS.NumField() ) // this doesn't work, why?

}

I'm just curious here. Why we need to get the type of the struct first before calling NumField()?

Why can't we just call it on the struct itself i.e. uS.NumField()?

From docs:

type Value struct {
        // contains filtered or unexported fields
}

func (v Value) NumField() int

I'm not quite get what is Value really means here. I do really appreciate concise explanation and examples.





Aucun commentaire:

Enregistrer un commentaire