gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:47:19 27 4
gpt4 key购买 nike

我希望在代码中使用结构 Dish 导出为 Dish。当未导出结构 dish 并且看不到其中未导出的字段时,我预计程序会失败。 (好的,我可以看到未导出的字段出现在导出的结构中,但即使这样似乎也是错误的)。

但是程序仍然可以正常工作??没有导出的反射包怎么能看到'dish'?

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

package main

import (
"fmt"
"reflect"
)

func main() {
// iterate through the attributes of a Data Model instance
for name, mtype := range attributes(&dish{}) {
fmt.Printf("Name: %s, Type: %s\n", name, mtype)
}
}

// Data Model
type dish struct {
Id int
last string
Name string
Origin string
Query func()
}

// Example of how to use Go's reflection
// Print the attributes of a Data Model
func attributes(m interface{}) map[string]reflect.Type {
typ := reflect.TypeOf(m)
// if a pointer to a struct is passed, get the type of the dereferenced object
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}

// create an attribute data structure as a map of types keyed by a string.
attrs := make(map[string]reflect.Type)
// Only structs are supported so return an empty result if the passed object
// isn't a struct
if typ.Kind() != reflect.Struct {
fmt.Printf("%v type can't have attributes inspected\n", typ.Kind())
return attrs
}

// loop through the struct's fields and set the map
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
fmt.Println("P = ", p)
if !p.Anonymous {
attrs[p.Name] = p.Type
}
}

return attrs
}

最佳答案

发件人:https://blog.golang.org/laws-of-reflection

the field names of T are upper case (exported) because only exported fields of a struct are settable."

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

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'?错误的;可以设置“ID”吗?真

关于类型(结构)名称的可见性(“dish”与“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()

关于go - 为什么反射要与 UNEXPORTED Struct 和 Unexported Fields 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37758699/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com