Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Created October 30, 2018 08:22
Show Gist options
  • Select an option

  • Save wuriyanto48/4dab8dbb5751f22f10a7e1af46ef8240 to your computer and use it in GitHub Desktop.

Select an option

Save wuriyanto48/4dab8dbb5751f22f10a7e1af46ef8240 to your computer and use it in GitHub Desktop.
how to achieve interface inheritance in go
package main
import (
"fmt"
"errors"
)
type Person struct {
ID string
Name string
}
type BaseRepository interface {
Save(interface{}) interface{}
}
type PersonRepository interface {
FindByID(string) (*Person, error)
BaseRepository
}
type PersonRepositoryMongo struct {
DB map[string]*Person
}
func (r *PersonRepositoryMongo) Save(data interface{}) interface{} {
person, ok := data.(*Person)
if !ok {
return errors.New("type is not person struct")
}
r.DB[person.ID] = person
return nil
}
func (r *PersonRepositoryMongo) FindByID(id string) (*Person, error) {
person, ok := r.DB[id]
if !ok {
return nil, errors.New("person not found")
}
return person, nil
}
func Process(r PersonRepository) {
p := &Person{
ID: "1",
Name: "Matius",
}
err := r.Save(p)
if err != nil {
fmt.Println(err)
}
person, err := r.FindByID("1")
if err != nil {
fmt.Println(err)
}
fmt.Println(person)
}
func main() {
db := make(map[string]*Person)
personRepoMongo := &PersonRepositoryMongo{db}
Process(personRepoMongo)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment