本文整理匯總了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)
}
示例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()))
}
}
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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))
}
}
示例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
}
示例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)
}
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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)
}
示例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
}