Collection

Run Settings
LanguageGo
Language Version
Run Command
package main import ( "fmt" ) func main() { exampleDefault() exampleCustomTypedCollection() } func exampleDefault() { c := Collection{data: make(map[int]Identifiable)} c.Set(Item{ID: 123}) c.Set(Foo{ID: 234}) fmt.Printf("%#v\n", c) entity, ok := c.Get(123) fmt.Printf("%#v %v\n", entity, ok) entity, ok = c.Get(234) fmt.Printf("%#v %v\n", entity, ok) entity, ok = c.Get(999) fmt.Printf("%#v %v\n", entity, ok) } func exampleCustomTypedCollection() { c := NewFooCollection() c.Set(Foo{ID: 123}) fmt.Printf("%#v\n", c) entity, ok := c.Get(123) fmt.Printf("%#v %v\n", entity, ok) entity, ok = c.Get(456) fmt.Printf("%#v %v\n", entity, ok) } // Interfaces. type Identifiable interface { Identify() int } type Collectable interface { Get(id int) (entity Identifiable, ok bool) Set(entity Identifiable) } // Base collection. type Collection struct { data map[int]Identifiable } func (collection Collection) Get(id int) (entity Identifiable, ok bool) { entity, ok = collection.data[id] return } func (collection Collection) Set(entity Identifiable) { collection.data[entity.Identify()] = entity } // Collection item. type Item struct { ID int Value string } func (item Item) Identify() int { return item.ID } // Typed collection. type FooCollection struct { Collection } func NewFooCollection() FooCollection { return FooCollection{Collection: Collection{data: make(map[int]Identifiable)}} } // Typed collection item. type Foo struct { ID int Data string } func (foo Foo) Identify() int { return foo.ID }
Editor Settings
Theme
Key bindings
Full width
Lines