本文整理汇总了Golang中reflect.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: mapCopy
func (d *decoder) mapCopy(src reflect.Value, dst reflect.Value) error {
sv := src.MapKeys()
dt := dst.Type().Elem()
for i := range sv {
ot := reflect.New(dt)
if dt.Kind() == reflect.Ptr {
ot = reflect.New(ot.Type().Elem())
}
d.pushPath(sv[i].String())
err := d.decode(src.MapIndex(sv[i]), ot)
if err != nil && err != ErrIncompatStruct {
err = errors.New(d.pathString() + err.Error())
d.path = nil
return err
}
d.popPath()
if err == nil {
dst.SetMapIndex(sv[i], ot.Elem())
}
}
return nil
}
示例2: ReadTargets
// ReadTargets reads targets into map entries.
func (n *MapNode) ReadTargets(c ReadContext, val Val) error {
list := c.List()
for _, keyStr := range list {
keyVal := reflect.New(n.KeyType).Elem()
if err := n.UnmarshalKey(keyStr, keyVal); err != nil {
return errors.Wrapf(err, "unmarshaling key")
}
elem := *n.ElemNode
elemContext := c.Push(keyStr)
elemVal := elem.NewKeyedVal(keyVal)
err := elem.Read(elemContext, elemVal)
// Set key field.
if n.Field != nil && n.Field.KeyField != "" {
n.Field.SetKeyFunc.Call([]reflect.Value{elemVal.Ptr, elemVal.Key})
}
if err != nil {
return errors.Wrapf(err, "reading child %s", keyStr)
}
// TODO: Don't calculate these values every time.
if reflect.DeepEqual(elemVal.Ptr.Elem().Interface(), reflect.New(elemVal.Ptr.Type().Elem()).Elem().Interface()) {
nv := reflect.New(elemVal.Ptr.Type()).Elem()
val.Ptr.Elem().SetMapIndex(elemVal.Key, nv)
} else {
val.Ptr.Elem().SetMapIndex(elemVal.Key, elemVal.Final())
}
}
return nil
}
示例3: TestUnmarshal
func (s *S) TestUnmarshal(c *C) {
for i, item := range unmarshalTests {
t := reflect.ValueOf(item.value).Type()
var value interface{}
switch t.Kind() {
case reflect.Map:
value = reflect.MakeMap(t).Interface()
case reflect.String:
t := reflect.ValueOf(item.value).Type()
v := reflect.New(t)
value = v.Interface()
default:
pt := reflect.ValueOf(item.value).Type()
pv := reflect.New(pt.Elem())
value = pv.Interface()
}
err := goyaml.Unmarshal([]byte(item.data), value)
c.Assert(err, IsNil, Commentf("Item #%d", i))
if t.Kind() == reflect.String {
c.Assert(*value.(*string), Equals, item.value, Commentf("Item #%d", i))
} else {
c.Assert(value, DeepEquals, item.value, Commentf("Item #%d", i))
}
}
}
示例4: Init
// Init initializes the container runtime given a JSON configuration that
// conforms to the Config set type.
func (c *CRT) Init(configStr string) error {
cfg := &Config{}
err := json.Unmarshal([]byte(configStr), cfg)
if err != nil {
return err
}
if _, ok := containerIfRegistry[cfg.CRT.Type]; !ok {
return core.Errorf("unregistered container run time")
}
crtConfigType := containerIfRegistry[cfg.CRT.Type].ConfigType
crtConfig := reflect.New(crtConfigType).Interface()
err = json.Unmarshal([]byte(configStr), crtConfig)
if err != nil {
return err
}
crtType := containerIfRegistry[cfg.CRT.Type].CRTType
crtif := reflect.New(crtType).Interface()
c.ContainerIf = crtif.(crtclient.ContainerIf)
err = c.ContainerIf.Init(&core.Config{V: crtConfig})
if err != nil {
return err
}
return nil
}
示例5: mapEncodeScratch
// mapEncodeScratch returns a new reflect.Value matching the map's value type,
// and a structPointer suitable for passing to an encoder or sizer.
func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
// Prepare addressable doubly-indirect placeholders for the key and value types.
// This is needed because the element-type encoders expect **T, but the map iteration produces T.
keycopy = reflect.New(mapType.Key()).Elem() // addressable K
keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
keyptr.Set(keycopy.Addr()) //
keybase = toStructPointer(keyptr.Addr()) // **K
// Value types are more varied and require special handling.
switch mapType.Elem().Kind() {
case reflect.Slice:
// []byte
var dummy []byte
valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
valbase = toStructPointer(valcopy.Addr())
case reflect.Ptr:
// message; the generated field type is map[K]*Msg (so V is *Msg),
// so we only need one level of indirection.
valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
valbase = toStructPointer(valcopy.Addr())
default:
// everything else
valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
valptr.Set(valcopy.Addr()) //
valbase = toStructPointer(valptr.Addr()) // **V
}
return
}
示例6: decodeMap
func decodeMap(v reflect.Value, x interface{}) {
t := v.Type()
if v.IsNil() {
v.Set(reflect.MakeMap(t))
}
for k, c := range getNode(x) {
i := reflect.New(t.Key()).Elem()
decodeValue(i, k)
w := v.MapIndex(i)
if w.IsValid() { // We have an actual element value to decode into.
if w.Kind() == reflect.Interface {
w = w.Elem()
}
w = reflect.New(w.Type()).Elem()
} else if t.Elem().Kind() != reflect.Interface { // The map's element type is concrete.
w = reflect.New(t.Elem()).Elem()
} else {
// The best we can do here is to decode as either a string (for scalars) or a map[string]interface {} (for the rest).
// We could try to guess the type based on the string (e.g. true/false => bool) but that'll get ugly fast,
// especially if we have to guess the kind (slice vs. array vs. map) and index type (e.g. string, int, etc.)
switch c.(type) {
case node:
w = reflect.MakeMap(stringMapType)
case string:
w = reflect.New(stringType).Elem()
default:
panic("value is neither node nor string")
}
}
decodeValue(w, c)
v.SetMapIndex(i, w)
}
}
示例7: TestUnmarshal
func TestUnmarshal(t *testing.T) {
for i, tt := range unmarshalTests {
var scan Scanner
in := []byte(tt.in)
if err := checkValid(in, &scan); err != nil {
if !reflect.DeepEqual(err, tt.err) {
t.Errorf("#%d: checkValid: %#v", i, err)
continue
}
}
if tt.ptr == nil {
continue
}
// v = new(right-type)
v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
dec := NewDecoder(bytes.NewReader(in))
if tt.useNumber {
dec.UseNumber()
}
if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) {
t.Errorf("#%d: %v, want %v", i, err, tt.err)
continue
} else if err != nil {
continue
}
if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out)
data, _ := Marshal(v.Elem().Interface())
println(string(data))
data, _ = Marshal(tt.out)
println(string(data))
continue
}
// Check round trip.
if tt.err == nil {
enc, err := Marshal(v.Interface())
if err != nil {
t.Errorf("#%d: error re-marshaling: %v", i, err)
continue
}
vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
dec = NewDecoder(bytes.NewReader(enc))
if tt.useNumber {
dec.UseNumber()
}
if err := dec.Decode(vv.Interface()); err != nil {
t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err)
continue
}
if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface())
t.Errorf(" In: %q", strings.Map(noSpace, string(in)))
t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc)))
continue
}
}
}
}
示例8: unmarshalMap
func unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error {
if data == nil {
return nil
}
mapData, ok := data.(map[string]interface{})
if !ok {
return fmt.Errorf("JSON value is not a map (%#v)", data)
}
t := value.Type()
if value.Kind() == reflect.Ptr {
t = t.Elem()
if value.IsNil() {
value.Set(reflect.New(t))
value.Elem().Set(reflect.MakeMap(t))
}
value = value.Elem()
}
for k, v := range mapData {
kvalue := reflect.ValueOf(k)
vvalue := reflect.New(value.Type().Elem()).Elem()
unmarshalAny(vvalue, v, "")
value.SetMapIndex(kvalue, vvalue)
}
return nil
}
示例9: callCustom
// callCustom calls 'custom' with sv & dv. custom must be a conversion function.
func (c *Converter) callCustom(sv, dv, custom reflect.Value, scope *scope) error {
if !sv.CanAddr() {
sv2 := reflect.New(sv.Type())
sv2.Elem().Set(sv)
sv = sv2
} else {
sv = sv.Addr()
}
if !dv.CanAddr() {
if !dv.CanSet() {
return scope.errorf("can't addr or set dest.")
}
dvOrig := dv
dv := reflect.New(dvOrig.Type())
defer func() { dvOrig.Set(dv) }()
} else {
dv = dv.Addr()
}
args := []reflect.Value{sv, dv, reflect.ValueOf(scope)}
ret := custom.Call(args)[0].Interface()
// This convolution is necessary because nil interfaces won't convert
// to errors.
if ret == nil {
return nil
}
return ret.(error)
}
示例10: bindRecvChan
// Internal function to bind receive operations for a channel.
func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) error {
chVal := reflect.ValueOf(channel)
if chVal.Kind() != reflect.Chan {
return ErrChanArg
}
argType := chVal.Type().Elem()
cb := func(m *Msg) {
var oPtr reflect.Value
if argType.Kind() != reflect.Ptr {
oPtr = reflect.New(argType)
} else {
oPtr = reflect.New(argType.Elem())
}
if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil {
c.Conn.err = errors.New("nats: Got an error trying to unmarshal: " + err.Error())
if c.Conn.Opts.AsyncErrorCB != nil {
go c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err)
}
return
}
if argType.Kind() != reflect.Ptr {
oPtr = reflect.Indirect(oPtr)
}
chVal.Send(oPtr)
}
_, err := c.Conn.subscribe(subject, queue, cb)
return err
}
示例11: RegisterRpcParams
func RegisterRpcParams(name string, obj interface{}) {
objType := reflect.TypeOf(obj)
if name == "" {
val := reflect.ValueOf(obj)
name = objType.Name()
if val.Kind() == reflect.Ptr {
name = objType.Elem().Name()
}
}
for i := 0; i < objType.NumMethod(); i++ {
method := objType.Method(i)
methodType := method.Type
if methodType.NumIn() == 3 { // if it has three parameters (one is self and two are rpc params)
out := methodType.In(2)
if out.Kind() == reflect.Ptr {
out = out.Elem()
}
rpcParamsMap[name+"."+method.Name] = &RpcParams{
Object: obj,
InParam: reflect.New(methodType.In(1)).Interface(),
OutParam: reflect.New(out).Interface(),
}
}
}
}
示例12: decodeSlice
func (d *Decoder) decodeSlice(s *decodStatus, v reflect.Value, t reflect.Type, tg tag) error {
if _, isInline := tg.Modifiers["inline"]; isInline {
val, ok := s.GetValue(d.env)
if !ok {
return nil
}
elements := d.arrSep.Split(val, -1)
slice := reflect.MakeSlice(t, 0, len(elements))
for _, s := range elements {
mv := reflect.New(t.Elem())
err := d.decodeField(mv.Elem(), s)
if err != nil {
return err
}
slice = reflect.Append(slice, mv.Elem())
}
v.Set(slice)
return nil
}
index := s.GetIndex()
slice := reflect.MakeSlice(t, 0, len(index))
for _, i := range index {
mv := reflect.New(t.Elem())
err := d.decodeElement(s, mv.Elem(), mv.Elem().Type(), tag{Name: strconv.Itoa(i), Modifiers: tg.Modifiers})
if err != nil {
return err
}
slice = reflect.Append(slice, mv.Elem())
}
v.Set(slice)
return nil
}
示例13: mapping
func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
if set := d.setter("!!map", &out, &good); set != nil {
defer set()
}
if out.Kind() == reflect.Struct {
return d.mappingStruct(n, out)
}
if out.Kind() == reflect.Interface {
// No type hints. Will have to use a generic map.
iface := out
out = settableValueOf(make(map[interface{}]interface{}))
iface.Set(out)
}
if out.Kind() != reflect.Map {
return false
}
outt := out.Type()
kt := outt.Key()
et := outt.Elem()
l := len(n.children)
for i := 0; i < l; i += 2 {
k := reflect.New(kt).Elem()
if d.unmarshal(n.children[i], k) {
e := reflect.New(et).Elem()
if d.unmarshal(n.children[i+1], e) {
out.SetMapIndex(k, e)
}
}
}
return true
}
示例14: decode
func (d *mapAsMapDecoder) decode(dv, sv reflect.Value) {
dt := dv.Type()
dv.Set(reflect.MakeMap(reflect.MapOf(dt.Key(), dt.Elem())))
var mapKey reflect.Value
var mapElem reflect.Value
keyType := dv.Type().Key()
elemType := dv.Type().Elem()
for _, sElemKey := range sv.MapKeys() {
var dElemKey reflect.Value
var dElemVal reflect.Value
if !mapKey.IsValid() {
mapKey = reflect.New(keyType).Elem()
} else {
mapKey.Set(reflect.Zero(keyType))
}
dElemKey = mapKey
if !mapElem.IsValid() {
mapElem = reflect.New(elemType).Elem()
} else {
mapElem.Set(reflect.Zero(elemType))
}
dElemVal = mapElem
d.keyDec(dElemKey, sElemKey)
d.elemDec(dElemVal, sv.MapIndex(sElemKey))
dv.SetMapIndex(dElemKey, dElemVal)
}
}
示例15: decodeMap
// decodeMap treats the next bytes as an XDR encoded variable array of 2-element
// structures whose fields are of the same type as the map keys and elements
// represented by the passed reflection value. Pointers are automatically
// indirected and allocated as necessary. It returns the the number of bytes
// actually read.
//
// An UnmarshalError is returned if any issues are encountered while decoding
// the elements.
func (d *Decoder) decodeMap(v reflect.Value) (int, error) {
dataLen, n, err := d.DecodeUint()
if err != nil {
return n, err
}
// Allocate storage for the underlying map if needed.
vt := v.Type()
if v.IsNil() {
v.Set(reflect.MakeMap(vt))
}
// Decode each key and value according to their type.
keyType := vt.Key()
elemType := vt.Elem()
for i := uint32(0); i < dataLen; i++ {
key := reflect.New(keyType).Elem()
n2, err := d.decode(key)
n += n2
if err != nil {
return n, err
}
val := reflect.New(elemType).Elem()
n2, err = d.decode(val)
n += n2
if err != nil {
return n, err
}
v.SetMapIndex(key, val)
}
return n, nil
}