背景:正在使用作为vmware的配置集合。我目前正在获取我需要的数据存储信息。我需要的字段之一是磁盘Naa。这可以在Vmfs字段下的VmfsDatastoreInfo结构中找到。
问题:,我正在循环通过一个范围,我相信Ds.Info是VmfsDatastoreInfo类型的,所以理论上我可以通过Ds.Info.Vmfs获得我所需要的信息。当我引用它时,我得到了错误:
ds.Info.Vmfs undefined (type types.BaseDatastoreInfo has no field or method Vmfs)出于好奇,我探索了使用反射,并做了以下工作:
fmt.Println(reflect.TypeOf(ds.Info))输出量
*types.VmfsDatastoreInfo我想弄明白为什么同一物体显示为两种不同的类型?
编辑:获得ds:
c, err := govmomi.NewClient(ctx, u, true)
//Check if the connection was successful
if err != nil {
fmt.Println(err)
}
// Create view of Datastore objects
m := view.NewManager(c.Client)
d, _ := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"Datastore"}, true)
if err != nil {
log.Fatal(err)
}
defer d.Destroy(ctx)
//Retrieve a list of all Virtual Machines including their summary and runtime
var dss []mo.Datastore
err = d.Retrieve(ctx, []string{"Datastore"}, []string{"info", "host"}, &dss)
if err != nil {
log.Fatal(err)
}
for _, ds := range dss {
fmt.Println(reflect.TypeOf(ds.Info))
s := reflect.ValueOf(ds.Info).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Println(i, typeOfT.Field(i).Name, f.Type(), f.Interface())
}
}ds是一种数据存储类型:
type Datastore struct {
ManagedEntity
Info types.BaseDatastoreInfo `mo:"info"`
Summary types.DatastoreSummary `mo:"summary"`
Host []types.DatastoreHostMount `mo:"host"`
Vm []types.ManagedObjectReference `mo:"vm"`
Browser types.ManagedObjectReference `mo:"browser"`
Capability types.DatastoreCapability `mo:"capability"`
IormConfiguration *types.StorageIORMInfo `mo:"iormConfiguration"`
}根据Govmomi软件包的信息,我发现了以下内容
type BaseDatastoreInfo interface {
GetDatastoreInfo() *DatastoreInfo
}
func (b *DatastoreInfo) GetDatastoreInfo() *DatastoreInfo
type DatastoreInfo struct {
DynamicData
Name string `xml:"name"`
Url string `xml:"url"`
FreeSpace int64 `xml:"freeSpace"`
MaxFileSize int64 `xml:"maxFileSize"`
MaxVirtualDiskCapacity int64 `xml:"maxVirtualDiskCapacity,omitempty"`
MaxMemoryFileSize int64 `xml:"maxMemoryFileSize,omitempty"`
Timestamp *time.Time `xml:"timestamp"`
ContainerId string `xml:"containerId,omitempty"`
}发布于 2018-10-11 08:31:41
我想弄明白为什么同一物体显示为两种不同的类型?
事实并非如此。
我认为Ds.Info是VmfsDatastoreInfo类型的
不是的。如果ds是一个Datastore,而ds.Info是一个类型的BaseDatastoreInfo,它是一个接口,因此只有一个方法GetDatastoreInfo()。这就是你看到错误的原因
ds.Info.Vmfs undefined (type types.BaseDatastoreInfo has no field or method Vmfs)现在阅读包反射的整个包文档和reflect.TypoOf文档。现在读https://blog.golang.org/laws-of-reflection。
reflect.TypeOf(ds.Info)解析ds.Info的动态类型(其静态类型为BaseDatastoreInfo)。有关一个简单的示例,请参见https://play.golang.org/p/kgDYXv4i63T。reflect.TypeOf查看其参数(即interface {})的内部;如果它不报告静态类型,reflect.TypeOf将始终报告interface{})。
也许您应该在没有反射的情况下使用该接口:
ds.Info.GetDatastoreInfo()并利用这些信息。不需要在这里反思。
https://stackoverflow.com/questions/52752589
复制相似问题