Created
October 30, 2018 08:22
-
-
Save wuriyanto48/4dab8dbb5751f22f10a7e1af46ef8240 to your computer and use it in GitHub Desktop.
how to achieve interface inheritance in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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