From the course: Go Recipes: Practical Projects
Go structs - Go Tutorial
From the course: Go Recipes: Practical Projects
Go structs
- When you need to define your own data types you will use structs. Let's look at the case where we have a home automation system and this system is sending events to your server. So let's say you have a door or maybe a thermostat sending events. Let's look at the code. You first define an event struct, which is common to all the events. It will have an ID for identifying the instrument and the Time where the event happened. And now we have events specific to instruments. So the door event is embedding the event meaning all of the events, fields like ID and Time can be accessed directly from DoorEvent, and it also has an action field which is a string on the temperature event. Again, embeds the event and it has its own value for the temperature value to create a new struct. We use a new function. This function is to get the parameters to create the struct. And here we can do validation. For example, if the ID is empty, we return an error and then we can create the event, the DoorEvent with embedded event, with the ID and Time and the action. And finally, we return a pointer to the event if you're coming from CNC, plus, plus this might seems odd, we're returning a pointer to something that is allocated on the stack. The Go compiler is doing Escape Analysis, and you'll find out that using the event outside of the function and we'll move it from the Stack to the Heap. And now we can use new event in our code. We create a new event for the front door, current Time and someone opened the door, and now we can print it out and you will see the embedded event with the ID and the Time. And also the action that belongs to the DoorEvent. Someone opened the door.
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
-
-
-
-
-