From the course: Go Recipes: Practical Projects
Unlock this course with a free trial
Join today to access over 25,300 courses taught by industry experts.
The empty interface - Go Tutorial
From the course: Go Recipes: Practical Projects
The empty interface
- [Instructor] Let's look at the JSON Marshal function. It's gets an empty interface and it turns a byte slice and a possible error. Json.Marshal can marshal several types, integers, strings, time.Time and others. These type don't share common methods. The only interface that satisfies them all is the empty interface. Rob Pike said "The empty interface says nothing." It's a way to bypass the goal type system and you should only use it as a last result. Let's have a look. Say I have several kinds of event. Let's say a ClickEvent and HoverEvent. And I have a counter for how many times each event was fired. The function to record that gets the empty interface because these two events and any other event in the system, do not have anything in common. And here we can do a type switch, checking what is the type of the current event. If it's a ClickEvent, we increment the contest for the click, and we increment the counter for hover. Otherwise we logout a warning. And now we can record…
Contents
-
-
-
-
-
-
Go structs1m 46s
-
(Locked)
Go methods1m 13s
-
(Locked)
Go interfaces1m 4s
-
(Locked)
The empty interface2m 12s
-
(Locked)
Working with iota in Go1m 31s
-
(Locked)
Structs, methods, and interfaces3m
-
(Locked)
Challenge: Structs, methods, and interfaces1m 30s
-
(Locked)
Solution: Structs, methods, and interfaces2m 10s
-
-
-
-
-