gitee.com/h79/goutils@v1.22.10/common/attributes/attributes.go (about) 1 package attributes 2 3 import "fmt" 4 5 // Attributes is an immutable struct for storing and retrieving generic 6 // key/value pairs. Keys must be hashable, and users should define their own 7 // types for keys. 8 type Attributes struct { 9 m map[interface{}]interface{} 10 } 11 12 // New returns a new Attributes containing all key/value pairs in kvs. If the 13 // same key appears multiple times, the last value overwrites all previous 14 // values for that key. Panics if len(kvs) is not even. 15 func New(kvs ...interface{}) *Attributes { 16 if len(kvs)%2 != 0 { 17 panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs))) 18 } 19 a := &Attributes{m: make(map[interface{}]interface{}, len(kvs)/2)} 20 for i := 0; i < len(kvs)/2; i++ { 21 a.m[kvs[i*2]] = kvs[i*2+1] 22 } 23 return a 24 } 25 26 // WithValues returns a new Attributes containing all key/value pairs in a and 27 // kvs. Panics if len(kvs) is not even. If the same key appears multiple 28 // times, the last value overwrites all previous values for that key. To 29 // remove an existing key, use a nil value. 30 func (a *Attributes) WithValues(kvs ...interface{}) *Attributes { 31 if a == nil { 32 return New(kvs...) 33 } 34 if len(kvs)%2 != 0 { 35 panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs))) 36 } 37 n := &Attributes{m: make(map[interface{}]interface{}, len(a.m)+len(kvs)/2)} 38 for k, v := range a.m { 39 n.m[k] = v 40 } 41 for i := 0; i < len(kvs)/2; i++ { 42 n.m[kvs[i*2]] = kvs[i*2+1] 43 } 44 return n 45 } 46 47 // Value returns the value associated with these attributes for key, or nil if 48 // no value is associated with key. 49 func (a *Attributes) Value(key interface{}) interface{} { 50 if a == nil { 51 return nil 52 } 53 return a.m[key] 54 } 55 56 func (a *Attributes) For(call func(key interface{}, val interface{})) { 57 if a == nil { 58 return 59 } 60 for k, v := range a.m { 61 call(k, v) 62 } 63 }