gogovmomi

How does golang do this?


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?


Solution

  • 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.