github.com/gogf/gf@v1.16.9/container/gtype/interface.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gtype 8 9 import ( 10 "github.com/gogf/gf/internal/json" 11 "github.com/gogf/gf/util/gconv" 12 "sync/atomic" 13 ) 14 15 // Interface is a struct for concurrent-safe operation for type interface{}. 16 type Interface struct { 17 value atomic.Value 18 } 19 20 // NewInterface creates and returns a concurrent-safe object for interface{} type, 21 // with given initial value <value>. 22 func NewInterface(value ...interface{}) *Interface { 23 t := &Interface{} 24 if len(value) > 0 && value[0] != nil { 25 t.value.Store(value[0]) 26 } 27 return t 28 } 29 30 // Clone clones and returns a new concurrent-safe object for interface{} type. 31 func (v *Interface) Clone() *Interface { 32 return NewInterface(v.Val()) 33 } 34 35 // Set atomically stores <value> into t.value and returns the previous value of t.value. 36 // Note: The parameter <value> cannot be nil. 37 func (v *Interface) Set(value interface{}) (old interface{}) { 38 old = v.Val() 39 v.value.Store(value) 40 return 41 } 42 43 // Val atomically loads and returns t.value. 44 func (v *Interface) Val() interface{} { 45 return v.value.Load() 46 } 47 48 // String implements String interface for string printing. 49 func (v *Interface) String() string { 50 return gconv.String(v.Val()) 51 } 52 53 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 54 func (v *Interface) MarshalJSON() ([]byte, error) { 55 return json.Marshal(v.Val()) 56 } 57 58 // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. 59 func (v *Interface) UnmarshalJSON(b []byte) error { 60 var i interface{} 61 err := json.UnmarshalUseNumber(b, &i) 62 if err != nil { 63 return err 64 } 65 v.Set(i) 66 return nil 67 } 68 69 // UnmarshalValue is an interface implement which sets any type of value for <v>. 70 func (v *Interface) UnmarshalValue(value interface{}) error { 71 v.Set(value) 72 return nil 73 }