Last active
December 29, 2015 21:29
-
-
Save c9s/7730292 to your computer and use it in GitHub Desktop.
This file contains 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" | |
type Contact struct { | |
Name string | |
Phone string | |
Age int | |
} | |
type Contacts []Contact | |
type Findable interface { | |
Find(name string) Contact | |
} | |
func (self *Contacts) AddContact(contact Contact) { | |
oldSlice := self | |
*self = append(*oldSlice, contact) | |
} | |
func (self Contacts) Find(name string) Contact { | |
for _, contact := range self { | |
if contact.Name == name { | |
return contact | |
} | |
} | |
return Contact{} | |
} | |
func FindContact(contacts interface{}, name string) { | |
if v, ok := contacts.(Findable); ok { | |
contact := v.Find(name) | |
fmt.Printf("Found %+v\n", contact) | |
} else { | |
fmt.Println("Interface not implemented") | |
} | |
} | |
func main() { | |
// contact := Contact{} | |
contacts := Contacts{} | |
contacts.AddContact(Contact{Name: "John"}) | |
fmt.Printf("%+v", contacts) | |
FindContact(contacts, "John") | |
// contacts := []Contact{} | |
// _ = contacts | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment