2014-10-02 90 views
2

我有一个接口:对于给定的接口,我有三个实现。这三种实现如何共享相同的方法?

type Reader interface { 
    // Read IV and Master header 
    ReadMaster(p []byte, full bool) (int, error) 

    // Read User header 
    ReadUser(p []byte, full bool) (int, error) 

    // Read Content data 
    ReadContent(p []byte) (int, error) 
} 

而且我有三个struct S跟接口兼容。所有三个结构都有samve方法ReadUser。所以我必须这样做:

func (r *s1) ReadUser(buf []byte, full bool) (int, error) { 
//.... code 1 .... 
} 
func (r *s2) ReadUser(buf []byte, full bool) (int, error) { 
//.... code 2 .... 
} 
func (r *s3) ReadUser(buf []byte, full bool) (int, error) { 
//.... code 3 .... 
} 

但是,上面的“code1”,“code2”和“code3”完全一样。有减少重复代码的好方法吗?例如。定义一次函数并将其分配给三个结构?

回答

7

用它自己的类型包装它。还记得Go中的接口应该只为小型特定任务提供合同。一个接口只包含一种方法是很常见的。

type UserReader interface { 
    ReadUser(p []byte, full bool) (int, error) 
} 

type UserRepo struct { 
} 

的方法添加到该类型:

func (ur *UserRepo) ReadUser(p []byte, full bool) (int, error) { 
    // code to read a user 
} 

然后,将它嵌入到你的其他类型:

type s1 struct { 
    *UserRepo 
    // other stuff here.. 
} 

type s2 struct { 
    *UserRepo 
    // other stuff here.. 
} 

type s3 struct { 
    *UserRepo 
    // other stuff here.. 
} 

然后,您可以:

u := s1{} 
i, err := u.ReadUser(..., ...) 

u2 := s2{} 
i2, err2 := u2.ReadUser(..., ...) 

// etc.. 

..你也可以这样做:

doStuff(u) 
doStuff(u2) 

..其中doStuff是:

func doStuff(u UserReader) { 
    // any of the three structs 
} 

Click here to see it in the Playground

相关问题