douqie1816 2018-07-23 08:21
浏览 1058

为什么Go反射NumField()仅在类型上可用?

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 getting what is Value really means here. I do really appreciate concise explanation and examples.

  • 写回答

2条回答 默认 最新

  • dongwuxie7976 2018-07-23 08:48
    关注

    NumField() is a function of reflected structs and can be applied on any struct once you have reflected it.

    It is NOT a function of User. You did not create any functions for User, so I did to try to clarify

    https://play.golang.org/p/c8oGa_56YfE

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!