I have an interface:
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)
}
And I have three struct
s are compatible with the interface. All the three structs have the samve method ReadUser
. So I have to do:
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 ....
}
However, the "code1", "code2" and "code3" above are exactly the same. It's there a good way to reduce the duplicate codes? E.g. define the function once and assign it to three struct?
Wrap it in its own type. Remembering too that interfaces in Go should only provide contracts for small specific tasks. It is very common for an interface to contain only a single method.
type UserReader interface {
ReadUser(p []byte, full bool) (int, error)
}
type UserRepo struct {
}
Add the method to that type:
func (ur *UserRepo) ReadUser(p []byte, full bool) (int, error) {
// code to read a user
}
Then, embed it in your other types:
type s1 struct {
*UserRepo
// other stuff here..
}
type s2 struct {
*UserRepo
// other stuff here..
}
type s3 struct {
*UserRepo
// other stuff here..
}
Then you can:
u := s1{}
i, err := u.ReadUser(..., ...)
u2 := s2{}
i2, err2 := u2.ReadUser(..., ...)
// etc..
..and you can also do:
doStuff(u)
doStuff(u2)
.. where doStuff
is:
func doStuff(u UserReader) {
// any of the three structs
}