From the course: Deep Dive Into Go Lang Interfaces

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Using reflection with the empty interface

Using reflection with the empty interface

From the course: Deep Dive Into Go Lang Interfaces

Using reflection with the empty interface

- [Instructor] If you get the empty interface as a parameter, you need to deduct what is the underlying type. And you have three options. You can use type assertion. We saw that in another video. We can use type switches, and you can use reflection, which means using the reflect package. Let's take a look at an example. I have two types, a log in event and an access event. And now I want to do unmarshaling of data into one of these events. So first thing I'm going to do is I want to make sure that what is being passed as "V" is a pointer. So I'm using the reflect package type of V and kind, and I want to make sure that it is a pointer. If it is not a pointer, json's unmarshal is going to fail. I want to catch it before that. And then I'm doing a type switch. This is "switchv.", and then the word "type" in parenthesis. And if it's a pointer to an access event or to login event, this is okay. Otherwise I'm going to return an error, "not supported type." And finally, I'm calling…

Contents