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.

Go methods

Go methods

- [Instructor] Once you define your own types, you can define methods on them. Methods are functions that are tied to a specific value. Let's look at the thermostat, for example. So, we define thermostat, which is a struct, it has an ID, which is a string which is exported, it starts with a capital letter, and we have value, which is not exported, it starts with a lowercase letter. And now we have a function. This function gets a receiver t, which has the type of pointer to thermostat, and it's called the value, it returns float64 and we return the internal value. We can also set the value on the thermostat by doing t.value = value. So whenever you're writing methods to change the struct, you need to use pointer receivers. Methods can also have just a type without a receiver, for example, when we asked the thermostat for its kind, we return thermostat. We don't really care of the specific thermostat. And here in main, we can create the thermostat. We can print out the ID and the…

Contents