works:programmer:go:interface-type
Типы interface{} и map. И способы их обработки
package main import ( "fmt" ) type Unit struct { memory map[string]interface{} } func NewUnit() *Unit { return &Unit{ make(map[string]interface{}), } } func (u *Unit) Get(name string) (interface{}, bool) { v, ok := u.memory[name] return v, ok } func (u *Unit) Set(name string, value interface{}) { u.memory[name] = value } func (u *Unit) TypeOf(name string) string { if val, ok := u.memory[name]; ok { switch v := val.(type) { case string: return "string" case bool: return "boolean" case int: return "integer" case float64: return "float" default: return fmt.Sprintf("other:%T", v) } } else { return "not exists" } } func main() { u := NewUnit() u.Set("ex", "строка") if ifc, ok := u.Get("ex"); ok { if s, ok := ifc.(string); ok { fmt.Println(s) } } }
works/programmer/go/interface-type.txt · Последнее изменение: 2019/04/21 23:49 — 127.0.0.1