课程: Go Essentials: Concurrency, Connectivity, and High-Performance Apps

Structs

- [Instructor] You can do a lot with the built-in types in Go, but there are times you'd like to define your own data structures. In Go, you will use extract to combine several fields into a data type. Let's assume you're keeping track on a campaign budget. So, here we have our budget, we say, type budget struct and then release the fields and their type. Here we have campaign ID, the balance, which is flow 64 and the expiration time. And now we have our budget, so B1 is the budget, the campaign is kittens, the balance is 22.3, US dollars, and the expiration time is seven days from now. And we are going to print out the budget. So, bringing up the command palette and start without debugging. And we see the budget is printed out with curly braces, kittens, the budget, and then the date. If you want to print more details on a budget, you can use the percent hash mark V. Once you do that, let's run this one again, you're going to see the type, then the curly basis and then the field name followed by the value in quoted format. If you want to access a single field from the budget, you can use the dot notation. The dot notation works both for structs and for pointers to struct. You can also create structs by specifying fields by name and not by position. Here we specify that the balance is $19 and 3 cents and the campaign ID is puppies. And notice that the expiration date is omitted. This is fine. When we you're going to print it out, you're going to see that we get the campaign ID puppies, the balance is 19.3 and the expiration time is the zero value for that field type. In our case, the expires type is time, and the zero value for time is January 1st, the year one. Finally, we can define the whole budget with the default values. So we define variable three as a budget, and we are going to print it out. And now all of the fields are going to be the zero value for that type. So the campaign ID is the empty string, the balance is zero, which is the zero value for floats, and again, the zero value for time. If you're coming from languages, such as Java or C plus plus, you might wonder if you can have private or protected fields which are not exposed outside of your package. In Go, this is very simple. Everything that starts with an upper case is accessible from outside the package. Otherwise it's accessible only from within the current package. In Go we call these exported and unexported symbols.

内容