Is it possible to inherit methods of a type without using embedded structs?
The discussion revolves around the concept of using embedded structs to gain access to methods of another type. The author notes that embedding a struct forces them to initialize the embedded struct when initializing the containing struct, which they find cumbersome. They provide code examples to demonstrate the issue and express their desire to avoid initializing the embedded struct explicitly.
The response addresses the technical limitation preventing inheritance without embedded structs. It explains that promoting methods from one type to another is only possible through embedding. The Go specification is cited as the authority, stating that the method set of a struct includes only methods declared with that struct as the receiver type.
The response then delves into the concept of promoted fields, which are fields of anonymous embedded structs that can be accessed directly through the containing struct. However, promoted fields cannot be used in composite literals, requiring explicit initialization when creating a struct containing an embedded anonymous field.
The answer acknowledges the limitations of using embedded structs and the absence of direct inheritance mechanisms in Go. It highlights that the primary reason for using embedded structs is to promote methods rather than data fields, as data can be accessed through composition.
The response humorously concludes with a personal greeting to the author, Jeff, referencing a previous interaction.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3