英文:
golang way to do inheritance, the workaround
问题
我理解,你想知道在Go语言中如何实现类似继承的功能。在Go语言中,虽然没有直接的继承机制,但可以通过嵌入结构体来实现类似的效果。你可以按照以下方式修改你的代码:
type CommonStruct struct{
ID string
}
type StructA struct{
CommonStruct
FieldA string
}
type StructB struct{
CommonStruct
FieldB string
}
func (s *CommonStruct) enrich(){
s.ID = IDGenerator()
}
func doSomething(s *CommonStruct){
s.enrich()
}
通过将CommonStruct
嵌入到StructA
和StructB
中,它们就可以访问CommonStruct
的字段和方法。然后,你可以像在doSomething
函数中那样,传递StructA
或StructB
的指针给doSomething
函数,从而重用enrich
方法。
英文:
I understand golang does not support inheritance, but what is the right way to do in go for the following?
type CommonStruct struct{
ID string
}
type StructA struct{
CommonStruct
FieldA string
}
type StructB struct{
CommonStruct
FieldB string
}
func (s *CommonStruct) enrich(){
s.ID = IDGenerator()
}
how I can reuse the code in enrich for all other "sub struct" if the following function?
func doSomthing(s *CommoStruct){
s.enrich()
}
答案1
得分: 7
你可以使用接口(interface):
type MyInterface interface {
enrich()
}
func doSomething(s MyInterface) {
s.enrich()
}
任何具有接口定义的每个函数或方法的结构体都被视为该接口的实例。现在你可以将任何具有 CommonStruct
的东西传递给 doSomething()
,因为 CommonStruct
定义了 enrich()
。如果你想要为特定的结构体重写 enrich()
,只需为该结构体定义 enrich()
。例如:
type CommonStruct struct {
ID string
}
type StructA struct {
*CommonStruct
}
type StructB struct {
*CommonStruct
}
type MyInterface interface {
enrich()
}
func doSomething(obj MyInterface) {
obj.enrich()
}
func (this *CommonStruct) enrich() {
fmt.Println("Common")
}
func (this *StructB) enrich() {
fmt.Println("Not Common")
}
func main() {
myA := &StructA{}
myB := &StructB{}
doSomething(myA)
doSomething(myB)
}
输出:
Common
Not Common
英文:
You can use an interface:
type MyInterface interface {
enrich()
}
func doSomthing(s MyInterface){
s.enrich()
}
Any struct that has each of the functions or methods of an interface defined is considered an instance of said interface. You could now pass anything with a CommonStruct
to doSomething()
, since CommonStruct
defined enrich()
. If you want to override enrich()
for a particular struct, simply define enrich()
for that struct. For example:
type CommonStruct struct{
ID string
}
type StructA struct{
*CommonStruct
}
type StructB struct{
*CommonStruct
}
type MyInterface interface {
enrich()
}
func doSomething(obj MyInterface) {
obj.enrich()
}
func (this *CommonStruct) enrich() {
fmt.Println("Common")
}
func (this *StructB) enrich() {
fmt.Println("Not Common")
}
func main() {
myA := &StructA{}
myB := &StructB{}
doSomething(myA)
doSomething(myB)
}
Prints:
> Common<br>
> Not Common
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论