当前位置: 首页>>代码示例>>Golang>>正文


Golang Value.MapIndex方法代码示例

本文整理汇总了Golang中reflect.Value.MapIndex方法的典型用法代码示例。如果您正苦于以下问题:Golang Value.MapIndex方法的具体用法?Golang Value.MapIndex怎么用?Golang Value.MapIndex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在reflect.Value的用法示例。


在下文中一共展示了Value.MapIndex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: deepCopyMap

func deepCopyMap(src, dst reflect.Value, t reflect.Type) {
	for _, key := range src.MapKeys() {
		var nkey, nval reflect.Value
		if key.IsValid() && key.CanSet() {
			if key.Kind() == reflect.Ptr {
				nkey = reflect.New(key.Elem().Type())
			} else {
				nkey = reflect.New(key.Type())
				nkey = reflect.Indirect(nkey)
			}
			s := reflect.Indirect(key)
			d := reflect.Indirect(nkey)
			tt := s.Type()
			deepCopy(s, d, tt)
		} else {
			nkey = key
		}
		if val := src.MapIndex(key); val.IsValid() && val.CanSet() {
			if val.Kind() == reflect.Ptr {
				nval = reflect.New(val.Elem().Type())
			} else {
				nval = reflect.New(val.Type())
				nval = reflect.Indirect(nval)
			}
			s := reflect.Indirect(val)
			d := reflect.Indirect(nval)
			tt := s.Type()
			deepCopy(s, d, tt)
		} else {
			nval = val
		}
		dst.SetMapIndex(nkey, nval)
	}
}
开发者ID:zwczou,项目名称:goserver,代码行数:34,代码来源:clone.go

示例2: 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)
	}
}
开发者ID:amasses,项目名称:form,代码行数:35,代码来源:decode.go

示例3: unmarshalDictionary

func (p *Decoder) unmarshalDictionary(pval *plistValue, val reflect.Value) {
	typ := val.Type()
	switch val.Kind() {
	case reflect.Struct:
		tinfo, err := getTypeInfo(typ)
		if err != nil {
			panic(err)
		}

		subvalues := pval.value.(*dictionary).m
		for _, finfo := range tinfo.fields {
			p.unmarshal(subvalues[finfo.name], finfo.value(val))
		}
	case reflect.Map:
		if val.IsNil() {
			val.Set(reflect.MakeMap(typ))
		}

		subvalues := pval.value.(*dictionary).m
		for k, sval := range subvalues {
			keyv := reflect.ValueOf(k).Convert(typ.Key())
			mapElem := val.MapIndex(keyv)
			if !mapElem.IsValid() {
				mapElem = reflect.New(typ.Elem()).Elem()
			}

			p.unmarshal(sval, mapElem)
			val.SetMapIndex(keyv, mapElem)
		}
	default:
		panic(&incompatibleDecodeTypeError{typ, pval.kind})
	}
}
开发者ID:QuocHuy7a10,项目名称:Arianrhod,代码行数:33,代码来源:unmarshal.go

示例4: display

func display(name string, v reflect.Value) {
	switch v.Kind() { //uint
	case reflect.Invalid:
		fmt.Printf("%s = invalid\n", name)
	case reflect.Slice, reflect.Array:
		for i := 0; i < v.Len(); i++ {
			display(fmt.Sprintf("%s[%d]", name, i), v.Index(i))
		}
	case reflect.Struct:
		for i := 0; i < v.NumField(); i++ {
			fieldPath := fmt.Sprintf("%s.%s", name, v.Type().Field(i).Name)
			display(fieldPath, v.Field(i))
		}
	case reflect.Map:
		for _, key := range v.MapKeys() {
			display(fmt.Sprintf("%s[%s]", name,
				formatAtom(key)), v.MapIndex(key))
		}
	case reflect.Ptr:
		if v.IsNil() {
			fmt.Printf("%s = nil\n", name)
		} else {
			display(fmt.Sprintf("(*%s)", name), v.Elem())
		}
	case reflect.Interface:
		if v.IsNil() {
			fmt.Printf("%s = nil\n", name)
		} else {
			fmt.Printf("%s.type = %s\n", name, v.Elem().Type())
			display(name+".value", v.Elem())
		}
	default: // basic types, channels, funcs
		fmt.Printf("%s = %s\n", name, formatAtom(v))
	}
}
开发者ID:hiromaily,项目名称:golibs,代码行数:35,代码来源:reflects_test.go

示例5: evalField

// evalField evaluates an expression like (.Field) or (.Field arg1 arg2).
// The 'final' argument represents the return value from the preceding
// value of the pipeline, if any.
func (s *state) evalField(dot reflect.Value, fieldName string, node parse.Node, args []parse.Node, final, receiver reflect.Value) reflect.Value {
	if !receiver.IsValid() {
		return zero
	}
	typ := receiver.Type()
	receiver, _ = indirect(receiver)
	// Unless it's an interface, need to get to a value of type *T to guarantee
	// we see all methods of T and *T.
	ptr := receiver
	if ptr.Kind() != reflect.Interface && ptr.CanAddr() {
		ptr = ptr.Addr()
	}
	if method := ptr.MethodByName(fieldName); method.IsValid() {
		return s.evalCall(dot, method, node, fieldName, args, final)
	}
	hasArgs := len(args) > 1 || final.IsValid()
	// It's not a method; must be a field of a struct or an element of a map. The receiver must not be nil.
	receiver, isNil := indirect(receiver)
	if isNil {
		s.errorf("nil pointer evaluating %s.%s", typ, fieldName)
	}
	switch receiver.Kind() {
	case reflect.Struct:
		tField, ok := receiver.Type().FieldByName(fieldName)
		if ok {
			field := receiver.FieldByIndex(tField.Index)
			if tField.PkgPath != "" { // field is unexported
				s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
			}
			// If it's a function, we must call it.
			if hasArgs {
				s.errorf("%s has arguments but cannot be invoked as function", fieldName)
			}
			return field
		}
		s.errorf("%s is not a field of struct type %s", fieldName, typ)
	case reflect.Map:
		// If it's a map, attempt to use the field name as a key.
		nameVal := reflect.ValueOf(fieldName)
		if nameVal.Type().AssignableTo(receiver.Type().Key()) {
			if hasArgs {
				s.errorf("%s is not a method but has arguments", fieldName)
			}
			result := receiver.MapIndex(nameVal)
			if !result.IsValid() {
				switch s.tmpl.option.missingKey {
				case mapInvalid:
					// Just use the invalid value.
				case mapZeroValue:
					result = reflect.Zero(receiver.Type().Elem())
				case mapError:
					s.errorf("map has no entry for key %q", fieldName)
				}
			}
			return result
		}
	}
	s.errorf("can't evaluate field %s in type %s", fieldName, typ)
	panic("not reached")
}
开发者ID:bibbyflyaway,项目名称:go,代码行数:63,代码来源:exec.go

示例6: encode

func (me *mapEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
	if v.IsNil() {
		e.WriteString("null")
		return
	}
	e.WriteByte('{')

	// Extract and sort the keys.
	keys := v.MapKeys()
	sv := make([]reflectWithString, len(keys))
	for i, v := range keys {
		sv[i].v = v
		if err := sv[i].resolve(); err != nil {
			e.error(&MarshalerError{v.Type(), err})
		}
	}
	sort.Sort(byString(sv))

	for i, kv := range sv {
		if i > 0 {
			e.WriteByte(',')
		}
		e.string(kv.s, opts.escapeHTML)
		e.WriteByte(':')
		me.elemEnc(e, v.MapIndex(kv.v), opts)
	}
	e.WriteByte('}')
}
开发者ID:2thetop,项目名称:go,代码行数:28,代码来源:encode.go

示例7: encodeMap

func encodeMap(val reflect.Value) ([]byte, error) {
	var t = val.Type()

	if t.Key().Kind() != reflect.String {
		return nil, fmt.Errorf("xmlrpc encode error: only maps with string keys are supported")
	}

	var b bytes.Buffer

	b.WriteString("<struct>")

	keys := val.MapKeys()

	for i := 0; i < val.Len(); i++ {
		key := keys[i]
		kval := val.MapIndex(key)

		b.WriteString("<member>")
		b.WriteString(fmt.Sprintf("<name>%s</name>", key.String()))

		p, err := encodeValue(kval)

		if err != nil {
			return nil, err
		}

		b.Write(p)
		b.WriteString("</member>")
	}

	b.WriteString("</struct>")

	return b.Bytes(), nil
}
开发者ID:imvu,项目名称:Tetra,代码行数:34,代码来源:encoder.go

示例8: decode

func (d *mapAsStructDecoder) decode(dv, sv reflect.Value) {
	for _, kv := range sv.MapKeys() {
		var f *field
		var fieldDec decoderFunc
		key := []byte(kv.String())
		for i := range d.fields {
			ff := &d.fields[i]
			ffd := d.fieldDecs[i]
			if bytes.Equal(ff.nameBytes, key) {
				f = ff
				fieldDec = ffd
				break
			}
			if f == nil && ff.equalFold(ff.nameBytes, key) {
				f = ff
				fieldDec = ffd
			}
		}

		if f == nil {
			continue
		}

		dElemVal := fieldByIndex(dv, f.index)
		sElemVal := sv.MapIndex(kv)

		if !sElemVal.IsValid() || !dElemVal.CanSet() {
			continue
		}

		fieldDec(dElemVal, sElemVal)
	}
}
开发者ID:kakamessi99,项目名称:shipyard,代码行数:33,代码来源:decoder_types.go

示例9: equalAny

// v1 and v2 are known to have the same type.
func equalAny(v1, v2 reflect.Value) bool {
	if v1.Type() == protoMessageType {
		m1, _ := v1.Interface().(Message)
		m2, _ := v2.Interface().(Message)
		return Equal(m1, m2)
	}
	switch v1.Kind() {
	case reflect.Bool:
		return v1.Bool() == v2.Bool()
	case reflect.Float32, reflect.Float64:
		return v1.Float() == v2.Float()
	case reflect.Int32, reflect.Int64:
		return v1.Int() == v2.Int()
	case reflect.Map:
		if v1.Len() != v2.Len() {
			return false
		}
		for _, key := range v1.MapKeys() {
			val2 := v2.MapIndex(key)
			if !val2.IsValid() {
				// This key was not found in the second map.
				return false
			}
			if !equalAny(v1.MapIndex(key), val2) {
				return false
			}
		}
		return true
	case reflect.Ptr:
		return equalAny(v1.Elem(), v2.Elem())
	case reflect.Slice:
		if v1.Type().Elem().Kind() == reflect.Uint8 {
			// short circuit: []byte
			if v1.IsNil() != v2.IsNil() {
				return false
			}
			return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
		}

		if v1.Len() != v2.Len() {
			return false
		}
		for i := 0; i < v1.Len(); i++ {
			if !equalAny(v1.Index(i), v2.Index(i)) {
				return false
			}
		}
		return true
	case reflect.String:
		return v1.Interface().(string) == v2.Interface().(string)
	case reflect.Struct:
		return equalStruct(v1, v2)
	case reflect.Uint32, reflect.Uint64:
		return v1.Uint() == v2.Uint()
	}

	// unknown type, so not a protocol buffer
	log.Printf("proto: don't know how to compare %v", v1)
	return false
}
开发者ID:Rachine,项目名称:imposm3,代码行数:61,代码来源:equal.go

示例10: 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
}
开发者ID:j0ju,项目名称:go-interfacetools,代码行数:26,代码来源:copier.go

示例11: reflectMap

func reflectMap(v reflect.Value) map[interface{}]interface{} {
	switch v.Kind() {
	case reflect.Struct:
		m := map[interface{}]interface{}{}
		for i := 0; i < v.NumField(); i++ {
			sf := v.Type().Field(i)
			if sf.PkgPath != "" && !sf.Anonymous {
				continue // unexported
			}

			k := sf.Name
			v := v.Field(i).Interface()

			m[k] = v
		}
		return m
	case reflect.Map:
		m := map[interface{}]interface{}{}
		for _, mk := range v.MapKeys() {
			k := ""
			if mk.Interface() != nil {
				k = fmt.Sprintf("%v", mk.Interface())
			}
			v := v.MapIndex(mk).Interface()

			m[k] = v
		}
		return m
	default:
		return nil
	}
}
开发者ID:freedmand,项目名称:doc.vu,代码行数:32,代码来源:compare.go

示例12: printMap

func printMap(w io.Writer, tv reflect.Value, depth string) {
	fmt.Fprintf(w, "{\n")
	ss := make(sort.StringSlice, tv.Len())
	i := 0
	for _, kval := range tv.MapKeys() {
		if kval.Kind() == reflect.Interface {
			kval = kval.Elem()
		}

		if kval.Kind() != reflect.String {
			continue
		}

		ss[i] = kval.String()
		i++
	}
	sort.Sort(ss)
	for _, k := range ss {
		val := tv.MapIndex(reflect.ValueOf(k))
		v := val.Interface()
		nd := depth + "  "
		for i := 0; i < len(k)+2; i++ {
			nd += " "
		}
		fmt.Fprintf(w, "  %s%s: ", depth, k)
		printValue(w, v, nd)
	}
	fmt.Fprintf(w, "%s}\n", depth)
}
开发者ID:Vorstack,项目名称:go-plist,代码行数:29,代码来源:prettyprint.go

示例13: retrieveValues

func (m Master) retrieveValues(db *sql.DB, rv reflect.Value, cfgs ...interface{}) (idField reflect.Value, fields []string, holders []string, values []interface{}, table string, err error) {
	table = strings.ToLower(rv.Type().Name()) + "s"
	// var insertNull bool
	for _, c := range cfgs {
		switch c.(type) {
		// case InsertNull:
		// 	insertNull = true
		case TableName:
			table = string(c.(TableName))
		}
	}

	// _ = insertNull
	switch rv.Kind() {
	case reflect.Struct:
		idField, fields, holders, values, err = m.walkStruct(rv)
	case reflect.Map:
		if rv.Type().Key().Kind() != reflect.String {
			err = fmt.Errorf("sqlkungfu: Insert(map key is %s, want string)", rv.Type().Key().Kind())
			return
		}
		for _, k := range rv.MapKeys() {
			fields = append(fields, m.quoteColumn(k.String()))
			holders = append(holders, "?")
			values = append(values, rv.MapIndex(k).Interface())
		}
	}
	return
}
开发者ID:valm0unt,项目名称:sqlkungfu,代码行数:29,代码来源:insert.go

示例14: reifyMap

func reifyMap(opts *options, to reflect.Value, from *Config) Error {
	if to.Type().Key().Kind() != reflect.String {
		return raiseKeyInvalidTypeUnpack(to.Type(), from)
	}

	if len(from.fields.fields) == 0 {
		return nil
	}

	if to.IsNil() {
		to.Set(reflect.MakeMap(to.Type()))
	}
	for k, value := range from.fields.fields {
		key := reflect.ValueOf(k)

		old := to.MapIndex(key)
		var v reflect.Value
		var err Error

		if !old.IsValid() {
			v, err = reifyValue(fieldOptions{opts: opts}, to.Type().Elem(), value)
		} else {
			v, err = reifyMergeValue(fieldOptions{opts: opts}, old, value)
		}

		if err != nil {
			return err
		}
		to.SetMapIndex(key, v)
	}

	return nil
}
开发者ID:ChongFeng,项目名称:beats,代码行数:33,代码来源:reify.go

示例15: genericLogData

// Pretty-print any random data we get back from the server
func genericLogData(name string, v reflect.Value, indent string, skip int) {
	prefix := "->" + indent
	if name != "" {
		prefix = "-> " + indent + name + ":"
	}

	// For pointers and interfaces, just grab the underlying value and try again
	if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
		genericLogData(name, v.Elem(), indent, skip)
		return
	}

	// Only print if skip is 0.  Recursive calls should indent or decrement skip, depending on if anything was
	// printed.
	var skipped bool
	if skip == 0 {
		skipped = false
		indent = indent + "  "
	} else {
		skipped = true
		skip = skip - 1
	}

	switch v.Kind() {
	case reflect.Struct:
		if !skipped {
			Log("%s\n", prefix)
		}
		for f := 0; f < v.NumField(); f++ {
			name := v.Type().Field(f).Name
			genericLogData(name, v.Field(f), indent, skip)
		}
	case reflect.Array:
		fallthrough
	case reflect.Slice:
		if !skipped {
			Log("%s\n", prefix)
		}
		for i := 0; i < v.Len(); i++ {
			genericLogData("", v.Index(i), indent, skip)
		}
	case reflect.Map:
		if !skipped {
			Log("%s\n", prefix)
		}
		for _, k := range v.MapKeys() {
			if name, ok := k.Interface().(string); ok {
				genericLogData(name, v.MapIndex(k), indent, skip)
			} else {
				genericLogData("Unknown field", v.MapIndex(k), indent, skip)
			}
		}
	default:
		if v.CanInterface() {
			Log("%s %v", prefix, v.Interface())
		} else {
			Log("%s <Invalid>", prefix)
		}
	}
}
开发者ID:irregular,项目名称:atlantis-manager,代码行数:61,代码来源:client.go


注:本文中的reflect.Value.MapIndex方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。