Golang是如何实现这个功能的?

huangapple go评论71阅读模式
英文:

How does golang do this?

问题

在使用govmomi时,我遇到了理解和访问ClusterComputeResourceSummary.UsageSummary字段的问题。后来我找到了一个链接,帮助我解决了这个问题。不过,我很好奇Golang是如何在幕后实现这个的,特别是在点操作符后面提供类型的部分,你必须在提取对象及其属性之前明确知道这个类型是什么?

usage := resource.Summary.(*types.ClusterComputeResourceSummary).UsageSummary 

我该如何理解这个语法,特别是在.(*types.ClusterComputeResourceSummary)之后的部分?

附言:对于问题的标题,请原谅我,老实说,我不知道这个用例的正确术语或行话,这类似于反射还是类似的东西吗?

英文:

After having issues understanding and being unable to access the ClusterComputeResourceSummary.UsageSummary field while working with govmomi, I was able to find a link that helped solve my problem, however, I am curious to understand how Golang is doing this behind the scenes, how after a chaining dot you provide the type you must obviously know before hand to extract the object and its properties?

usage := resource.Summary.(*types.ClusterComputeResourceSummary).UsageSummary 

How can I go about reading this syntax, especially the part after .(*types.ClusterComputeResourceSummary) ?

P.S. Forgive me for the question title, honestly I don't know the right term or lingo for this use case, like is this reflection or something similar?

答案1

得分: 0

这是一个"类型断言"。resource.Summary 是一个包含指向对象和其类型的接口值。类型断言会检查你给定的 *types.ClusterComputeResourcesSummary 类型是否可以赋值给接口中存储的数据类型,如果可以,就将接口中存储的值作为该类型的实例返回。然后你可以访问该变量的成员/方法。

英文:

This is a "type assertion". The resource.Summary is an interface value that contains a pointer to an object, and its type. The type assertion checks if the type you gave *types.ClusterComputeResourcesSummary can be assigned to the type of data stored in the interface, and if so, returns the value stored in the interface as an instance of that type. Then you can access the members/methods of that variable.

huangapple
  • 本文由 发表于 2022年8月9日 04:04:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73283441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定