为什么反射与UNEXPORTED Struct和Unexported Fields一起使用?

时间:2016-06-11 00:08:13

标签: go

我希望在代码中使用struct Dish 导出为Dish。 当结构未被导出并且看不到其中未导出的字段时,我预计程序会失败。 (好吧,我可以看到未导出的字段出现在导出的结构中,但即使这看起来也不对)。

但程序仍然如图所示?如果反射包是未被移植的,它怎么能看到'碟'?

--------------程序遵循----------     //修改示例来自博客:http://merbist.com/2011/06/27/golang-reflection-exampl/

input id="id1" class="ng-pristine ng-invalid ng-invalid-required 
  ng-valid-pattern" type="text" ng-focus=""  
  ng-pattern="/^[0-9]{10,19}$/" required="" 
  ng-change="event1(Method1.id1)" ng-model="Method1.id1"
  placeholder="1234123412341*" 
  ng-class="{'active': !method21.id1.$pristine}" name="id1"

1 个答案:

答案 0 :(得分:1)

来自:https://blog.golang.org/laws-of-reflection

  

T的字段名称是大写(导出),因为只有结构的导出字段是可设置的。"

这很容易显示和证明这个概念:

fmt.Printf("can set 'last'? %v; can set 'Id'? %v",
    reflect.ValueOf(&dish{}).Elem().FieldByName("last").CanSet(),
    reflect.ValueOf(&dish{}).Elem().FieldByName("Id").CanSet(),
)

打印:can set 'last'? false; can set 'Id'? true

关于类型(结构)名称的可见性(" dish" vs" Dish")仅在编译时直接使用类型时影响可见性。例如:

import "whatever/something"
...
v := something.someStruct{} // will give compile error
...
// this can return an instance of someStruct, which can be inspected
// with reflect just like any other struct (and that works fine because
// we haven't directly put a literal "something.someStruct" in this code
v := something.SomeFunc()