课程: Treating Go as an Object-Oriented Language

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Composition

Composition

- [Instructor] We already talked about that Go doesn't support inheritance, but it does support composition. So let's talk about the details of composition itself. First of all, it's extremely easy to use. It allows you to share logic from one struct to another. In the same way, it allows you to share data. Now, this is very useful for common patterns that exist on multiple structs. For instance, I use this a lot when dealing with writing audit logic to my database tables. The audit fields are in a struct, and then that struct is composed into every data table representation. Therefore, I get shared behavior across multiple data table structs from the composed struct. Now it's time to talk a little bit about how to actually use it. You start by building a struct. You then include that struct in another struct as an attribute. It can be either named or unnamed. Methods of the struct appear as though they are on the…

内容