本文整理汇总了Golang中reflect.MakeZero函数的典型用法代码示例。如果您正苦于以下问题:Golang MakeZero函数的具体用法?Golang MakeZero怎么用?Golang MakeZero使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MakeZero函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: decodeInterface
// decodeInterface receives the name of a concrete type followed by its value.
// If the name is empty, the value is nil and no value is sent.
func (dec *Decoder) decodeInterface(ityp *reflect.InterfaceType, state *decodeState, p uintptr, indir int) {
// Create an interface reflect.Value. We need one even for the nil case.
ivalue := reflect.MakeZero(ityp).(*reflect.InterfaceValue)
// Read the name of the concrete type.
b := make([]byte, state.decodeUint())
state.b.Read(b)
name := string(b)
if name == "" {
// Copy the representation of the nil interface value to the target.
// This is horribly unsafe and special.
*(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.Get()
return
}
// The concrete type must be registered.
typ, ok := nameToConcreteType[name]
if !ok {
errorf("gob: name not registered for interface: %q", name)
}
// Read the concrete value.
value := reflect.MakeZero(typ)
dec.decodeValueFromBuffer(value, false, true)
if dec.err != nil {
error(dec.err)
}
// Allocate the destination interface value.
if indir > 0 {
p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect
}
// Assign the concrete value to the interface.
// Tread carefully; it might not satisfy the interface.
setInterfaceValue(ivalue, value)
// Copy the representation of the interface value to the target.
// This is horribly unsafe and special.
*(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.Get()
}
示例2: Demarshal
func (jm *jsonDemarshaler) Demarshal() (id Id, ctrlMsg interface{}, appMsg reflect.Value, err os.Error) {
seedId := jm.proxy.router.seedId
id, _ = seedId.Clone()
if err = jm.Decode(id); err != nil {
return
}
if id.Scope() == NumScope && id.Member() == NumMembership {
return
}
switch id.SysIdIndex() {
case ConnId, DisconnId, ErrorId:
idc, _ := seedId.Clone()
ctrlMsg = &ConnInfoMsg{Id: idc}
err = jm.demarshalCtrlMsg(ctrlMsg)
case ReadyId:
idc, _ := seedId.Clone()
ctrlMsg = &ConnReadyMsg{[]*ChanReadyInfo{&ChanReadyInfo{Id: idc}}}
err = jm.demarshalCtrlMsg(ctrlMsg)
case PubId, UnPubId, SubId, UnSubId:
idc, _ := seedId.Clone()
ctrlMsg = &IdChanInfoMsg{[]*IdChanInfo{&IdChanInfo{idc, nil, nil}}}
err = jm.demarshalCtrlMsg(ctrlMsg)
default: //appMsg
chanType := jm.proxy.getExportRecvChanType(id)
if chanType == nil {
err = os.ErrorString(fmt.Sprintf("failed to find chanType for id %v", id))
return
}
et := chanType.Elem()
appMsg = reflect.MakeZero(et)
var ptrT *reflect.PtrValue
switch et := et.(type) {
case *reflect.BoolType:
ptrT = jm.ptrBool
ptrT.PointTo(appMsg)
case *reflect.IntType:
ptrT = jm.ptrInt
ptrT.PointTo(appMsg)
case *reflect.FloatType:
ptrT = jm.ptrFloat
ptrT.PointTo(appMsg)
case *reflect.StringType:
ptrT = jm.ptrString
ptrT.PointTo(appMsg)
case *reflect.PtrType:
sto := reflect.MakeZero(et.Elem())
ptrT = appMsg.(*reflect.PtrValue)
ptrT.PointTo(sto)
default:
err = os.ErrorString(fmt.Sprintf("invalid chanType for id %v", id))
return
}
err = jm.Decode(ptrT.Interface())
}
return
}
示例3: TestUnmarshal
func TestUnmarshal(t *testing.T) {
for i, test := range unmarshalTestData {
pv := reflect.MakeZero(reflect.NewValue(test.out).Type())
zv := reflect.MakeZero(pv.Type().(*reflect.PtrType).Elem())
pv.(*reflect.PtrValue).PointTo(zv)
val := pv.Interface()
err := Unmarshal(val, test.in)
if err != nil {
t.Errorf("Unmarshal failed at index %d %v", i, err)
}
if !reflect.DeepEqual(val, test.out) {
t.Errorf("#%d:\nhave %#v\nwant %#v", i, val, test.out)
}
}
}
示例4: subst
// subst returns a copy of pattern with values from m substituted in place
// of wildcards and pos used as the position of tokens from the pattern.
// if m == nil, subst returns a copy of pattern and doesn't change the line
// number information.
func subst(m map[string]reflect.Value, pattern reflect.Value, pos reflect.Value) reflect.Value {
if pattern == nil {
return nil
}
// Wildcard gets replaced with map value.
if m != nil && pattern.Type() == identType {
name := pattern.Interface().(*ast.Ident).Name()
if isWildcard(name) {
if old, ok := m[name]; ok {
return subst(nil, old, nil)
}
}
}
if pos != nil && pattern.Type() == positionType {
return pos
}
// Otherwise copy.
switch p := pattern.(type) {
case *reflect.SliceValue:
v := reflect.MakeSlice(p.Type().(*reflect.SliceType), p.Len(), p.Len())
for i := 0; i < p.Len(); i++ {
v.Elem(i).SetValue(subst(m, p.Elem(i), pos))
}
return v
case *reflect.StructValue:
v := reflect.MakeZero(p.Type()).(*reflect.StructValue)
for i := 0; i < p.NumField(); i++ {
v.Field(i).SetValue(subst(m, p.Field(i), pos))
}
return v
case *reflect.PtrValue:
v := reflect.MakeZero(p.Type()).(*reflect.PtrValue)
v.PointTo(subst(m, p.Elem(), pos))
return v
case *reflect.InterfaceValue:
v := reflect.MakeZero(p.Type()).(*reflect.InterfaceValue)
v.SetValue(subst(m, p.Elem(), pos))
return v
}
return pattern
}
示例5: writeToContainer
func writeToContainer(data [][]byte, val reflect.Value) os.Error {
switch v := val.(type) {
case *reflect.PtrValue:
return writeToContainer(data, reflect.Indirect(v))
case *reflect.InterfaceValue:
return writeToContainer(data, v.Elem())
case *reflect.MapValue:
if _, ok := v.Type().(*reflect.MapType).Key().(*reflect.StringType); !ok {
return os.NewError("Invalid map type")
}
elemtype := v.Type().(*reflect.MapType).Elem()
for i := 0; i < len(data)/2; i++ {
mk := reflect.NewValue(string(data[i*2]))
mv := reflect.MakeZero(elemtype)
writeTo(data[i*2+1], mv)
v.SetElem(mk, mv)
}
case *reflect.StructValue:
for i := 0; i < len(data)/2; i++ {
name := string(data[i*2])
field := v.FieldByName(name)
if field == nil {
continue
}
writeTo(data[i*2+1], field)
}
default:
return os.NewError("Invalid container type")
}
return nil
}
示例6: TestUnmarshal
func TestUnmarshal(t *testing.T) {
var scan scanner
for i, tt := range unmarshalTests {
in := []byte(tt.in)
if err := checkValid(in, &scan); err != nil {
t.Errorf("#%d: checkValid: %v", i, err)
continue
}
// v = new(right-type)
v := reflect.NewValue(tt.ptr).(*reflect.PtrValue)
v.PointTo(reflect.MakeZero(v.Type().(*reflect.PtrType).Elem()))
if err := Unmarshal([]byte(in), v.Interface()); err != nil {
t.Errorf("#%d: %v", i, err)
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))
return
continue
}
}
}
示例7: Key
func (b *structBuilder) Key(k string) Builder {
if b == nil {
return nobuilder
}
switch v := reflect.Indirect(b.val).(type) {
case *reflect.StructValue:
t := v.Type().(*reflect.StructType)
// Case-insensitive field lookup.
k = strings.ToLower(k)
for i := 0; i < t.NumField(); i++ {
if strings.ToLower(t.Field(i).Name) == k {
return &structBuilder{val: v.Field(i)}
}
}
case *reflect.MapValue:
t := v.Type().(*reflect.MapType)
if t.Key() != reflect.Typeof(k) {
break
}
key := reflect.NewValue(k)
elem := v.Elem(key)
if elem == nil {
v.SetElem(key, reflect.MakeZero(t.Elem()))
elem = v.Elem(key)
}
return &structBuilder{val: elem, map_: v, key: key}
}
return nobuilder
}
示例8: ImportNValues
// ImportNValues imports a channel of the given type and specified direction
// and then receives or transmits up to n values on that channel. A value of
// n==0 implies an unbounded number of values. The channel to be bound to
// the remote site's channel is provided in the call and may be of arbitrary
// channel type.
// Despite the literal signature, the effective signature is
// ImportNValues(name string, chT chan T, dir Dir, pT T)
// where T must be a struct, pointer to struct, etc. pT may be more indirect
// than the value type of the channel (e.g. chan T, pT *T) but it must be a
// pointer.
// Example usage:
// imp, err := NewImporter("tcp", "netchanserver.mydomain.com:1234")
// if err != nil { log.Exit(err) }
// ch := make(chan myType)
// err := imp.ImportNValues("name", ch, Recv, new(myType), 1)
// if err != nil { log.Exit(err) }
// fmt.Printf("%+v\n", <-ch)
// (TODO: Can we eliminate the need for pT?)
func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, pT interface{}, n int) os.Error {
ch, err := checkChan(chT, dir)
if err != nil {
return err
}
// Make sure pT is a pointer (to a pointer...) to a struct.
rt := reflect.Typeof(pT)
if _, ok := rt.(*reflect.PtrType); !ok {
return os.ErrorString("not a pointer:" + rt.String())
}
if _, ok := reflect.Indirect(reflect.NewValue(pT)).(*reflect.StructValue); !ok {
return os.ErrorString("not a pointer to a struct:" + rt.String())
}
imp.chanLock.Lock()
defer imp.chanLock.Unlock()
_, present := imp.chans[name]
if present {
return os.ErrorString("channel name already being imported:" + name)
}
ptr := reflect.MakeZero(reflect.Typeof(pT)).(*reflect.PtrValue)
imp.chans[name] = &importChan{ch, dir, ptr, n}
// Tell the other side about this channel.
req := new(request)
req.name = name
req.dir = dir
req.count = n
if err := imp.encode(req, nil); err != nil {
log.Stderr("importer request encode:", err)
return err
}
return nil
}
示例9: GetAll
func (c *Conn) GetAll(rowsSlicePtr interface{}, condition string, args ...interface{}) os.Error {
sliceValue, ok := reflect.Indirect(reflect.NewValue(rowsSlicePtr)).(*reflect.SliceValue)
if !ok {
return os.NewError("needs a pointer to a slice")
}
sliceElementType := sliceValue.Type().(*reflect.SliceType).Elem()
condition = strings.TrimSpace(condition)
if len(condition) > 0 {
condition = fmt.Sprintf("where %v", condition)
}
resultsSlice, err := c.getResultsForQuery(getTableName(rowsSlicePtr), condition, args)
if err != nil {
return err
}
for _, results := range resultsSlice {
newValue := reflect.MakeZero(sliceElementType)
scanMapIntoStruct(newValue.Addr().Interface(), results)
sliceValue.SetValue(reflect.Append(sliceValue, newValue))
}
return nil
}
示例10: run
// Handle the data from a single imported data stream, which will
// have the form
// (response, data)*
// The response identifies by name which channel is receiving data.
// TODO: allow an importer to send.
func (imp *Importer) run() {
// Loop on responses; requests are sent by ImportNValues()
resp := new(response)
for {
if err := imp.decode(resp); err != nil {
log.Stderr("importer response decode:", err)
break
}
if resp.error != "" {
log.Stderr("importer response error:", resp.error)
// TODO: tear down connection
break
}
imp.chanLock.Lock()
ich, ok := imp.chans[resp.name]
imp.chanLock.Unlock()
if !ok {
log.Stderr("unknown name in request:", resp.name)
break
}
if ich.dir != Recv {
log.Stderr("TODO: import send unimplemented")
break
}
// Create a new value for each received item.
val := reflect.MakeZero(ich.ptr.Type().(*reflect.PtrType).Elem())
ich.ptr.PointTo(val)
if err := imp.decode(ich.ptr.Interface()); err != nil {
log.Stderr("importer value decode:", err)
return
}
ich.ch.Send(val)
}
}
示例11: TestDecodeStruct
func TestDecodeStruct(t *testing.T) {
for i, bt := range bsonTests {
if bt.psv == nil {
continue
}
pt := reflect.NewValue(bt.psv).Type().(*reflect.PtrType)
psv := reflect.MakeZero(pt).(*reflect.PtrValue)
psv.PointTo(reflect.MakeZero(pt.Elem()))
err := Decode(bt.data, psv.Interface())
sv := psv.Elem().Interface()
if err != nil {
t.Errorf("%d: error decoding %q: %s", i, bt.data, err)
} else if !reflect.DeepEqual(sv, bt.sv) {
t.Errorf("%d: data=%q,\n\texpected %q\n\tactual %q", i, bt.data, bt.sv, sv)
}
}
}
示例12: decodeMap
func (dec *Decoder) decodeMap(mtyp *reflect.MapType, state *decodeState, p uintptr, keyOp, elemOp decOp, indir, keyIndir, elemIndir int, ovfl os.ErrorString) {
if indir > 0 {
p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect
}
up := unsafe.Pointer(p)
if *(*unsafe.Pointer)(up) == nil { // maps are represented as a pointer in the runtime
// Allocate map.
*(*unsafe.Pointer)(up) = unsafe.Pointer(reflect.MakeMap(mtyp).Get())
}
// Maps cannot be accessed by moving addresses around the way
// that slices etc. can. We must recover a full reflection value for
// the iteration.
v := reflect.NewValue(unsafe.Unreflect(mtyp, unsafe.Pointer((p)))).(*reflect.MapValue)
n := int(state.decodeUint())
for i := 0; i < n; i++ {
key := decodeIntoValue(state, keyOp, keyIndir, reflect.MakeZero(mtyp.Key()), ovfl)
elem := decodeIntoValue(state, elemOp, elemIndir, reflect.MakeZero(mtyp.Elem()), ovfl)
v.SetElem(key, elem)
}
}
示例13: serveSend
// Receive and deliver locally one item from a client asking for a Send
// The header is passed by value to avoid issues of overwriting.
func (client *expClient) serveSend(hdr header) {
ech := client.getChan(&hdr, Recv)
if ech == nil {
return
}
// Create a new value for each received item.
val := reflect.MakeZero(ech.ch.Type().(*reflect.ChanType).Elem())
if err := client.decode(val); err != nil {
expLog("value decode:", err)
return
}
ech.ch.Send(val)
}
示例14: Key
func (self *structBuilder) Key(k string) Builder {
if self == nil {
return nobuilder
}
switch v := reflect.Indirect(self.val).(type) {
case *reflect.StructValue:
t := v.Type().(*reflect.StructType)
// Case-insensitive field lookup.
k = strings.ToLower(k)
for i := 0; i < t.NumField(); i++ {
if strings.ToLower(t.Field(i).Name) == k {
return &structBuilder{val: v.Field(i)}
}
}
case *reflect.MapValue:
t := v.Type().(*reflect.MapType)
if t.Key() != reflect.Typeof(k) {
break
}
key := reflect.NewValue(k)
elem := v.Elem(key)
if elem == nil {
v.SetElem(key, reflect.MakeZero(t.Elem()))
elem = v.Elem(key)
}
return &structBuilder{val: elem, map_: v, key: key}
case *reflect.SliceValue:
index, err := strconv.Atoi(k)
if err != nil {
return nobuilder
}
if index < v.Len() {
return &structBuilder{val: v.Elem(index)}
}
if index < v.Cap() {
v.SetLen(index + 1)
return &structBuilder{val: v.Elem(index)}
}
newCap := v.Cap() * 2
if index >= newCap {
newCap = index*2 + 1
}
temp := reflect.MakeSlice(v.Type().(*reflect.SliceType), index+1, newCap)
reflect.ArrayCopy(temp, v)
v.Set(temp)
return &structBuilder{val: v.Elem(index)}
}
return nobuilder
}
示例15: checkUnmarshal
func checkUnmarshal(expected string, data any) (err os.Error) {
if err = checkMarshal(expected, data); err != nil {
return
}
dataValue := reflect.NewValue(data)
newOne := reflect.MakeZero(dataValue.Type())
buf := bytes.NewBufferString(expected)
if err = UnmarshalValue(buf, newOne); err != nil {
return
}
if err = checkFuzzyEqualValue(dataValue, newOne); err != nil {
return
}
return
}