Skip to content

Instantly share code, notes, and snippets.

@c9s
Last active December 29, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c9s/7730292 to your computer and use it in GitHub Desktop.
Save c9s/7730292 to your computer and use it in GitHub Desktop.
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