當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Value.Elem方法代碼示例

本文整理匯總了Golang中reflect.Value.Elem方法的典型用法代碼示例。如果您正苦於以下問題:Golang Value.Elem方法的具體用法?Golang Value.Elem怎麽用?Golang Value.Elem使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在reflect.Value的用法示例。


在下文中一共展示了Value.Elem方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: encode

func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
	if v.IsNil() {
		e.WriteString("null")
		return
	}
	pe.elemEnc(e, v.Elem(), opts)
}
開發者ID:2thetop,項目名稱:go,代碼行數:7,代碼來源:encode.go

示例2: defaultReturnHandler

func defaultReturnHandler() ReturnHandler {
	return func(ctx *Context, vals []reflect.Value) {
		rv := ctx.GetVal(inject.InterfaceOf((*http.ResponseWriter)(nil)))
		resp := rv.Interface().(http.ResponseWriter)
		var respVal reflect.Value
		if len(vals) > 1 && vals[0].Kind() == reflect.Int {
			resp.WriteHeader(int(vals[0].Int()))
			respVal = vals[1]
		} else if len(vals) > 0 {
			respVal = vals[0]

			if isError(respVal) {
				err := respVal.Interface().(error)
				if err != nil {
					ctx.internalServerError(ctx, err)
				}
				return
			} else if canDeref(respVal) {
				if respVal.IsNil() {
					return // Ignore nil error
				}
			}
		}
		if canDeref(respVal) {
			respVal = respVal.Elem()
		}
		if isByteSlice(respVal) {
			resp.Write(respVal.Bytes())
		} else {
			resp.Write([]byte(respVal.String()))
		}
	}
}
開發者ID:RezaDKhan,項目名稱:terraform,代碼行數:33,代碼來源:return_handler.go

示例3: validateFieldMin

// Validates that if a value is provided for a field, that value must be at
// least a minimum length.
func validateFieldMin(f reflect.StructField, fvalue reflect.Value) error {
	minStr := f.Tag.Get("min")
	if minStr == "" {
		return nil
	}
	min, _ := strconv.ParseInt(minStr, 10, 64)

	kind := fvalue.Kind()
	if kind == reflect.Ptr {
		if fvalue.IsNil() {
			return nil
		}
		fvalue = fvalue.Elem()
	}

	switch fvalue.Kind() {
	case reflect.String:
		if int64(fvalue.Len()) < min {
			return fmt.Errorf("field too short, minimum length %d", min)
		}
	case reflect.Slice, reflect.Map:
		if fvalue.IsNil() {
			return nil
		}
		if int64(fvalue.Len()) < min {
			return fmt.Errorf("field too short, minimum length %d", min)
		}

		// TODO min can also apply to number minimum value.

	}
	return nil
}
開發者ID:anthonyrisinger,項目名稱:rack,代碼行數:35,代碼來源:param_validator.go

示例4: encode

func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
	if v.IsNil() {
		e.WriteString("null")
		return
	}
	pe.elemEnc(e, v.Elem(), quoted)
}
開發者ID:ossrs,項目名稱:go-oryx-lib,代碼行數:7,代碼來源:encode.go

示例5: indirect

// rv must be a non-nil pointer or a settable value
func indirect(rv reflect.Value) (reflect.Value, error) {
	for {
		if rv.Kind() == reflect.Interface && !rv.IsNil() {
			if e := rv.Elem(); e.Kind() == reflect.Ptr && !e.IsNil() {
				rv = e.Elem()
			}
		}

		if rv.Kind() == reflect.Map && rv.IsNil() {
			rv.Set(reflect.MakeMap(rv.Type()))
		}

		if rv.Kind() != reflect.Ptr {
			break
		}

		if rv.IsNil() {
			rv.Set(reflect.New(rv.Type().Elem()))
		}
		rv = rv.Elem()
	}
	if k := rv.Kind(); k != reflect.Struct && k != reflect.Map {
		return reflect.Value{}, &InvalidIndirectError{rv.Type()}
	}
	if rv.Kind() == reflect.Map {
		if t := rv.Type(); t.Key().Kind() != reflect.String || t.Elem().Kind() != reflect.String {
			return reflect.Value{}, &InvalidIndirectError{t}
		}
	}
	return rv, nil
}
開發者ID:coolwust,項目名稱:env,代碼行數:32,代碼來源:env.go

示例6: decodeMessage

func decodeMessage(chunk []byte, st *SprotoType, v reflect.Value) (int, error) {
	var total int
	var tags []Tag
	var err error
	if total, tags, err = decodeHeader(chunk); err != nil {
		return 0, err
	}

	for _, tag := range tags {
		var used int
		var data []byte
		if tag.Val == nil {
			if used, data, err = readChunk(chunk[total:]); err != nil {
				return 0, err
			}
			total += used
		}
		sf := st.FieldByTag(int(tag.Tag))
		if sf == nil {
			fmt.Fprintf(os.Stderr, "sproto<%s>: unknown tag %d\n", st.Name, tag.Tag)
			continue
		}
		v1 := v.Elem().FieldByIndex(sf.index)
		if err = sf.dec(tag.Val, data, sf, v1); err != nil {
			return 0, err
		}
	}
	return total, nil
}
開發者ID:shitfSign,項目名稱:gosproto,代碼行數:29,代碼來源:decode.go

示例7: encodeField

func encodeField(w io.Writer, f reflect.Value) error {
	if f.Type() == timeType {
		return encodeTime(w, f)
	}

	switch f.Kind() {
	case reflect.Uint8:
		fallthrough
	case reflect.Uint16:
		fallthrough
	case reflect.Uint32:
		fallthrough
	case reflect.Uint64:
		fallthrough
	case reflect.Int64:
		fallthrough
	case reflect.Int32:
		fallthrough
	case reflect.Int16:
		fallthrough
	case reflect.Int8:
		return binary.Write(w, byteOrder, f.Interface())
	case reflect.String:
		return encodeStrField(w, f)
	case reflect.Slice:
		return encodeArray(w, f)
	case reflect.Interface:
		return encodeField(w, f.Elem())
	default:
		panic(fmt.Sprintf("unimplemented kind %v", f))
	}
}
開發者ID:YoshikuniShiku,項目名稱:go-mtpfs,代碼行數:32,代碼來源:encoding.go

示例8: getFields

func getFields(v reflect.Value, tagName string) []*Field {
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}

	t := v.Type()

	var fields []*Field

	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)

		if tag := field.Tag.Get(tagName); tag == "-" {
			continue
		}

		f := &Field{
			field: field,
			value: v.FieldByName(field.Name),
		}

		fields = append(fields, f)

	}

	return fields
}
開發者ID:vincentaubert,項目名稱:vault,代碼行數:27,代碼來源:structs.go

示例9: binaryMarshal

func (f *encFnInfo) binaryMarshal(rv reflect.Value) {
	var bm binaryMarshaler
	if f.ti.mIndir == 0 {
		bm = rv.Interface().(binaryMarshaler)
	} else if f.ti.mIndir == -1 {
		bm = rv.Addr().Interface().(binaryMarshaler)
	} else {
		for j, k := int8(0), f.ti.mIndir; j < k; j++ {
			if rv.IsNil() {
				f.ee.encodeNil()
				return
			}
			rv = rv.Elem()
		}
		bm = rv.Interface().(binaryMarshaler)
	}
	// debugf(">>>> binaryMarshaler: %T", rv.Interface())
	bs, fnerr := bm.MarshalBinary()
	if fnerr != nil {
		panic(fnerr)
	}
	if bs == nil {
		f.ee.encodeNil()
	} else {
		f.ee.encodeStringBytes(c_RAW, bs)
	}
}
開發者ID:MG-RAST,項目名稱:Shock,代碼行數:27,代碼來源:encode.go

示例10: indirect

// indirect walks down v allocating pointers as needed,
// until it gets to a non-pointer.
func indirect(v reflect.Value) reflect.Value {
	// If v is a named type and is addressable,
	// start with its address, so that if the type has pointer methods,
	// we find them.
	if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
		v = v.Addr()
	}
	for {
		// Load value from interface, but only if the result will be
		// usefully addressable.
		if v.Kind() == reflect.Interface && !v.IsNil() {
			e := v.Elem()
			if e.Kind() == reflect.Ptr && !e.IsNil() && e.Elem().Kind() == reflect.Ptr {
				v = e
				continue
			}
		}

		if v.Kind() != reflect.Ptr {
			break
		}

		if v.IsNil() {
			v.Set(reflect.New(v.Type().Elem()))
		}
		v = v.Elem()
	}
	return v
}
開發者ID:joamaki,項目名稱:gorethink,代碼行數:31,代碼來源:decoder.go

示例11: DeserializeToValue

func DeserializeToValue(r io.Reader, dsize int, dst reflect.Value) error {

	//fmt.Printf("*A1 v is type %s \n", data.Type().String() )		//this is the type of the value

	var v reflect.Value
	switch dst.Kind() {
	case reflect.Ptr:
		v = dst.Elem()
	case reflect.Slice:
		v = dst
	case reflect.Struct:

	default:
		return errors.New("binary.Read: invalid type " + reflect.TypeOf(dst).String())
	}

	//fmt.Printf("*A2 v is type %s \n", v.Type().String() )		//this is the type of the value

	d1 := &decoder{buf: make([]byte, dsize)}
	if _, err := io.ReadFull(r, d1.buf); err != nil {
		return err
	}

	return d1.value(v)
}
開發者ID:Chao-Jia,項目名稱:skycoin,代碼行數:25,代碼來源:encoder.go

示例12: DeserializeRawToValue

// Returns number of bytes used and an error if deserialization failed
func DeserializeRawToValue(in []byte, dst reflect.Value) (int, error) {
	var v reflect.Value
	switch dst.Kind() {
	case reflect.Ptr:
		v = dst.Elem()
	case reflect.Slice:
		v = dst
	case reflect.Struct:
	default:
		return 0, errors.New("binary.Read: invalid type " + reflect.TypeOf(dst).String())
	}

	inlen := len(in)
	d1 := &decoder{buf: make([]byte, inlen)}
	copy(d1.buf, in)

	//check if can deserialize
	d2 := &decoder{buf: make([]byte, inlen)}
	copy(d2.buf, d1.buf)
	if d2.dchk(v) != 0 {
		return 0, errors.New("Deserialization failed")
	}

	err := d1.value(v)
	return inlen - len(d1.buf), err
}
開發者ID:Chao-Jia,項目名稱:skycoin,代碼行數:27,代碼來源:encoder.go

示例13: flatten

func (c *FlatMapConfig) flatten(result map[string]interface{}, prefix string, v reflect.Value) error {
	var err error

	if v.Kind() == reflect.Interface {
		v = v.Elem()
	}

	// Set as type interface
	// https://golang.org/pkg/reflect/#Kind
	switch v.Kind() {
	case reflect.Bool:
		result[c.keyDelim+prefix] = v.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
		result[c.keyDelim+prefix] = v.Int()
	case reflect.String:
		result[c.keyDelim+prefix] = v.String()
	case reflect.Map:
		err = c.flattenMap(result, prefix, v)
	case reflect.Slice, reflect.Array:
		err = c.flattenSlice(result, prefix, v)
	default:
		err = fmt.Errorf("Unknown primitive type found for value: '%q'", v)
	}

	return err
}
開發者ID:turtlemonvh,項目名稱:mapmap,代碼行數:26,代碼來源:flatten.go

示例14: writeStruct

func (enc *encoder) writeStruct(val reflect.Value) {
	for val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface {
		val = val.Elem()
	}
	if val.Kind() != reflect.Struct {
		enc.error(&UnsupportedValueError{Value: val, Message: "expect a struct"})
	}
	marker := &MStruct{}
	if err := enc.proto.WriteStructBegin(enc.writer, marker); err != nil {
		enc.error(err)
	}
	for _, ef := range encodeFields(val.Type()).fields {
		field := val.Type().Field(ef.i)
		fieldValue := val.Field(ef.i)

		if isEmptyValue(fieldValue) {
			continue
		}

		mfield := &MField{Name: field.Name, Type: ef.fieldType, ID: ef.id}
		if err := enc.proto.WriteFieldBegin(enc.writer, mfield); err != nil {
			enc.error(err)
		}
		enc.writeValue(fieldValue, ef.fieldType)
	}
	enc.proto.WriteFieldStop(enc.writer)
}
開發者ID:msglib,項目名稱:msglib-go,代碼行數:27,代碼來源:serializer.go

示例15: convertToFloat64

func convertToFloat64(depth int, v reflect.Value) (float64, bool) {
	if v.Kind() == reflect.Interface {
		v = v.Elem()
	}
	switch v.Kind() {
	case reflect.Float32, reflect.Float64:
		return v.Float(), true
	case reflect.Int16, reflect.Int8, reflect.Int, reflect.Int32, reflect.Int64:
		return float64(v.Int()), true
	case reflect.String:
		s := v.String()
		var f float64
		var err error
		if strings.HasPrefix(s, "0x") {
			f, err = strconv.ParseFloat(s, 64)
		} else {
			f, err = strconv.ParseFloat(s, 64)
		}
		if err == nil {
			return float64(f), true
		}
		if depth == 0 {
			s = intStrReplacer.Replace(s)
			rv := reflect.ValueOf(s)
			return convertToFloat64(1, rv)
		}
	case reflect.Slice:
		// Should we grab first one?  Or Error?
		//u.Warnf("ToFloat() but is slice?: %T first=%v", v, v.Index(0))
		return convertToFloat64(0, v.Index(0))
	default:
		//u.Warnf("Cannot convert type?  %v", v.Kind())
	}
	return math.NaN(), false
}
開發者ID:kyledj,項目名稱:qlbridge,代碼行數:35,代碼來源:coerce.go


注:本文中的reflect.Value.Elem方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。