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


Golang reflect.PtrTo函数代码示例

本文整理汇总了Golang中reflect.PtrTo函数的典型用法代码示例。如果您正苦于以下问题:Golang PtrTo函数的具体用法?Golang PtrTo怎么用?Golang PtrTo使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: getColumnsAsScope

func (scope *Scope) getColumnsAsScope(column string) *Scope {
	values := scope.IndirectValue()
	switch values.Kind() {
	case reflect.Slice:
		modelType := values.Type().Elem()
		if modelType.Kind() == reflect.Ptr {
			modelType = modelType.Elem()
		}
		fieldStruct, _ := modelType.FieldByName(column)
		var columns reflect.Value
		if fieldStruct.Type.Kind() == reflect.Slice || fieldStruct.Type.Kind() == reflect.Ptr {
			columns = reflect.New(reflect.SliceOf(reflect.PtrTo(fieldStruct.Type.Elem()))).Elem()
		} else {
			columns = reflect.New(reflect.SliceOf(reflect.PtrTo(fieldStruct.Type))).Elem()
		}
		for i := 0; i < values.Len(); i++ {
			column := reflect.Indirect(values.Index(i)).FieldByName(column)
			if column.Kind() == reflect.Ptr {
				column = column.Elem()
			}
			if column.Kind() == reflect.Slice {
				for i := 0; i < column.Len(); i++ {
					columns = reflect.Append(columns, column.Index(i).Addr())
				}
			} else {
				columns = reflect.Append(columns, column.Addr())
			}
		}
		return scope.New(columns.Interface())
	case reflect.Struct:
		return scope.New(values.FieldByName(column).Addr().Interface())
	}
	return nil
}
开发者ID:useidel,项目名称:notary,代码行数:34,代码来源:preload.go

示例2: 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
}
开发者ID:spxtr,项目名称:contrib,代码行数:32,代码来源:encode.go

示例3: makeDecoder

func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) {
	kind := typ.Kind()
	switch {
	case typ == rawValueType:
		return decodeRawValue, nil
	case typ.Implements(decoderInterface):
		return decodeDecoder, nil
	case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(decoderInterface):
		return decodeDecoderNoPtr, nil
	case typ.AssignableTo(reflect.PtrTo(bigInt)):
		return decodeBigInt, nil
	case typ.AssignableTo(bigInt):
		return decodeBigIntNoPtr, nil
	case isUint(kind):
		return decodeUint, nil
	case kind == reflect.Bool:
		return decodeBool, nil
	case kind == reflect.String:
		return decodeString, nil
	case kind == reflect.Slice || kind == reflect.Array:
		return makeListDecoder(typ, tags)
	case kind == reflect.Struct:
		return makeStructDecoder(typ)
	case kind == reflect.Ptr:
		if tags.nilOK {
			return makeOptionalPtrDecoder(typ)
		}
		return makePtrDecoder(typ)
	case kind == reflect.Interface:
		return decodeInterface, nil
	default:
		return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
	}
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:34,代码来源:decode.go

示例4: makeWriter

// makeWriter creates a writer function for the given type.
func makeWriter(typ reflect.Type) (writer, error) {
	kind := typ.Kind()
	switch {
	case typ.Implements(encoderInterface):
		return writeEncoder, nil
	case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(encoderInterface):
		return writeEncoderNoPtr, nil
	case kind == reflect.Interface:
		return writeInterface, nil
	case typ.AssignableTo(reflect.PtrTo(bigInt)):
		return writeBigIntPtr, nil
	case typ.AssignableTo(bigInt):
		return writeBigIntNoPtr, nil
	case isUint(kind):
		return writeUint, nil
	case kind == reflect.Bool:
		return writeBool, nil
	case kind == reflect.String:
		return writeString, nil
	case kind == reflect.Slice && isByte(typ.Elem()):
		return writeBytes, nil
	case kind == reflect.Array && isByte(typ.Elem()):
		return writeByteArray, nil
	case kind == reflect.Slice || kind == reflect.Array:
		return makeSliceWriter(typ)
	case kind == reflect.Struct:
		return makeStructWriter(typ)
	case kind == reflect.Ptr:
		return makePtrWriter(typ)
	default:
		return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
	}
}
开发者ID:este-xx,项目名称:go-expanse,代码行数:34,代码来源:encode.go

示例5: reflectPtrTo

func reflectPtrTo() {
	tInt := reflect.TypeOf(3)
	tPtrInt := reflect.PtrTo(tInt)
	print(reflect.Zero(tPtrInt)) // @types *int
	tPtrPtrInt := reflect.PtrTo(tPtrInt)
	print(reflect.Zero(tPtrPtrInt)) // @types **int
}
开发者ID:2722,项目名称:lantern,代码行数:7,代码来源:arrayreflect.go

示例6: GetValuesForSqlRowScan

func (p *model) GetValuesForSqlRowScan(cols []string) []interface{} {
	var values = make([]interface{}, len(cols))

	for index, column := range cols {
		if field, ok := p.Fields[column]; ok {
			if field.IsJsonb() {
				var vs []byte
				values[index] = &vs
			} else if field.Field.Kind() == reflect.Ptr {
				values[index] = field.Field.Addr().Interface()
			} else if field.Field.Kind() == reflect.String {
				values[index] = reflect.New(reflect.PtrTo(reflect.TypeOf(""))).Interface()
			} else if field.Field.Kind() == reflect.Struct {
				switch field.Field.Type().String() {
				//				case "time.Time":
				//					values[index] = reflect.New(reflect.PtrTo(reflect.TypeOf(""))).Interface()
				default:
					values[index] = reflect.New(reflect.PtrTo(field.Field.Type())).Interface()
				}
			} else {
				values[index] = reflect.New(reflect.PtrTo(field.Field.Type())).Interface()
			}
		} else {
			var i interface{}
			values[index] = &i
		}
	}
	return values
}
开发者ID:eynStudio,项目名称:gobreak,代码行数:29,代码来源:model.go

示例7: Into

func (jd *joinDeclaration) Into(dest interface{}) *joinDeclaration {
	var r *Relation
	rt := reflect.TypeOf(r).Elem()

	dt := reflect.TypeOf(dest)
	if !dt.Implements(rt) {
		panic(fmt.Sprintf("Into() param: %#v, type: %v"+
			", does not implement Relation", dest, dt))
	}

	jd.into = dest.(Relation)

	var out reflect.Type
	if jd.selectWhereFunc != nil {
		out = reflect.TypeOf(jd.selectWhereFunc).Out(0)
	} else if len(jd.sources) == 1 {
		out = reflect.PtrTo(jd.sources[0].TupleType())
	} else {
		panic(fmt.Sprintf("unexpected Into() join declaration: %#v", jd))
	}
	if jd.selectWhereFlat {
		if out != dt {
			panic(fmt.Sprintf("Into() param: %#v, type: %v, does not match"+
				" output type: %v", dest, dt, out))
		}
	} else {
		if out != jd.into.TupleType() &&
			out != reflect.PtrTo(jd.into.TupleType()) {
			panic(fmt.Sprintf("Into() param: %#v, type: %v, does not match"+
				" tuple type: %v", dest, dt, out))
		}
	}

	return jd
}
开发者ID:steveyen,项目名称:gdec,代码行数:35,代码来源:gdec.go

示例8: checkUnaryExpr

func checkUnaryExpr(ctx *Ctx, unary *ast.UnaryExpr, env *Env) (*UnaryExpr, []error) {
	aexpr := &UnaryExpr{UnaryExpr: unary}

	x, errs := CheckExpr(ctx, unary.X, env)
	if errs == nil || x.IsConst() {
		if t, err := expectSingleType(ctx, x.KnownType(), x); err != nil {
			errs = append(errs, err)
		} else if unary.Op == token.AND { // address of
			if !isAddressableOrCompositeLit(x) {
				printableX := fakeCheckExpr(unary.X, env)
				printableX.setKnownType(knownType{t})
				errs = append(errs, ErrInvalidAddressOf{at(ctx, printableX)})
			}
			t := x.KnownType()[0]
			if ct, ok := t.(ConstType); ok {
				if ct == ConstNil {
					errs = append(errs, ErrUntypedNil{at(ctx, x)})
				} else {
					ptrT := reflect.PtrTo(unhackType(ct.DefaultPromotion()))
					aexpr.knownType = knownType{ptrT}
				}
			} else {
				ptrT := reflect.PtrTo(unhackType(t))
				aexpr.knownType = knownType{ptrT}
			}
			aexpr.X = x
		} else if unary.Op == token.ARROW { // <-
			if (t.Kind() != reflect.Chan) || (t.ChanDir()|reflect.RecvDir == 0) {
				errs = append(errs, ErrInvalidRecvFrom{at(ctx, x)})
			}
		} else {
			aexpr.X = x
			// All numeric and bool unary expressions do not change type
			aexpr.knownType = knownType(x.KnownType())
			if x.IsConst() {
				if ct, ok := t.(ConstType); ok {
					c, moreErrs := evalConstUnaryExpr(ctx, aexpr, x, ct)
					if moreErrs != nil {
						errs = append(errs, moreErrs...)
					}
					aexpr.constValue = c

				} else {
					c, moreErrs := evalConstTypedUnaryExpr(ctx, aexpr, x)
					if moreErrs != nil {
						errs = append(errs, moreErrs...)
					}
					aexpr.constValue = c
				}
			} else {
				if !isUnaryOpDefinedOn(unary.Op, t) {
					errs = append(errs, ErrInvalidUnaryOperation{at(ctx, unary)})
				}
			}
		}
	}
	aexpr.X = x
	return aexpr, errs
}
开发者ID:rocky,项目名称:go-eval,代码行数:59,代码来源:checkunaryexpr.go

示例9: implementsInterface

func implementsInterface(t reflect.Type) bool {
	return t.Implements(decoderType) ||
		reflect.PtrTo(t).Implements(decoderType) ||
		t.Implements(setterType) ||
		reflect.PtrTo(t).Implements(setterType) ||
		t.Implements(unmarshalerType) ||
		reflect.PtrTo(t).Implements(unmarshalerType)
}
开发者ID:kelseyhightower,项目名称:envconfig,代码行数:8,代码来源:usage.go

示例10: newTypeEncoder

// newTypeEncoder constructs an encoderFunc for a type.
// The returned encoder only checks CanAddr when allowAddr is true.
func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
	if t.Implements(marshalerType) {
		return marshalerEncoder
	}
	if t.Kind() != reflect.Ptr && allowAddr {
		if reflect.PtrTo(t).Implements(marshalerType) {
			return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false))
		}
	}

	if t.Implements(jsonMarshalerType) {
		return jsonMarshalerEncoder
	}
	if t.Kind() != reflect.Ptr && allowAddr {
		if reflect.PtrTo(t).Implements(jsonMarshalerType) {
			return newCondAddrEncoder(addrJsonMarshalerEncoder, newTypeEncoder(t, false))
		}
	}

	if t.Implements(textMarshalerType) {
		return textMarshalerEncoder
	}
	if t.Kind() != reflect.Ptr && allowAddr {
		if reflect.PtrTo(t).Implements(textMarshalerType) {
			return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false))
		}
	}

	switch t.Kind() {
	case reflect.Bool:
		return boolEncoder
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return intEncoder
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return uintEncoder
	case reflect.Float32:
		return float32Encoder
	case reflect.Float64:
		return float64Encoder
	case reflect.String:
		return stringEncoder
	case reflect.Interface:
		return interfaceEncoder
	case reflect.Struct:
		return newStructEncoder(t)
	case reflect.Map:
		return newMapEncoder(t)
	case reflect.Slice:
		return newSliceEncoder(t)
	case reflect.Array:
		return newArrayEncoder(t)
	case reflect.Ptr:
		return newPtrEncoder(t)
	default:
		return unsupportedTypeEncoder
	}
}
开发者ID:cesanta,项目名称:ubjson,代码行数:59,代码来源:encode.go

示例11: TypeMatch

// A simple check of type comparison.  Ptr to a struct and struct are
// considered compatible.  This is useful mostly for the cases where
// we have interface implementations
func TypeMatch(this interface{}, that interface{}) bool {
	t1 := reflect.TypeOf(this)
	t2 := reflect.TypeOf(that)
	if t1 == t2 {
		return true
	}
	if reflect.PtrTo(t1) == t2 || t1 == reflect.PtrTo(t2) {
		return true
	}
	return false
}
开发者ID:qorio,项目名称:omni,代码行数:14,代码来源:typecheck.go

示例12: isRecursive

func isRecursive(v reflect.Value) bool {
	ind := reflect.Indirect(v)
	t := v.Type()
	if ind.Kind() != reflect.Struct {
		return false
	}
	for i := 0; i < ind.Type().NumField(); i++ {
		ft := ind.Field(i).Type()
		return ft == t || ft == reflect.PtrTo(t) || t.AssignableTo(ft) || reflect.PtrTo(t).AssignableTo(ft)
	}
	return false
}
开发者ID:fcavani,项目名称:monlite,代码行数:12,代码来源:types.go

示例13: wantMarshal

func (i *Inception) wantMarshal(si *StructInfo) bool {
	if si.Options.SkipEncoder {
		return false
	}
	typ := si.Typ
	mlx := typ.Implements(marshalerFasterType) || reflect.PtrTo(typ).Implements(marshalerFasterType)
	mlstd := typ.Implements(marshalerType) || reflect.PtrTo(typ).Implements(marshalerType)
	if mlstd && !mlx {
		// structure has MarshalJSON, but not our faster version -- skip it.
		return false
	}
	return true
}
开发者ID:pquerna,项目名称:ffjson,代码行数:13,代码来源:inception.go

示例14: Find

/*
Find sets the fields of values to the matches of the patterns specified for them in Compile.
values must be a pointer to the same type of struct as used in Compile.
Returns true if there is at least 1 field match.

Fields for which no match is found will not be modified, so you can specify default values by
just setting fields on values before passing it to this method.
*/
func (r *TypedRegexp) Find(s string, values interface{}) (found bool) {
	t := reflect.TypeOf(r.captureGroups)
	ptr := reflect.ValueOf(values)

	if ptr.Type() != reflect.PtrTo(t) {
		panic(fmt.Errorf("values must be %s, is %s", reflect.PtrTo(t), ptr.Type()))
	}

	submatches := r.pattern.FindStringSubmatch(s)
	if len(submatches) == 0 {
		return false
	}
	r.assignSubmatchesToStruct(submatches, &ptr)
	return true
}
开发者ID:zach-klippenstein,项目名称:go-typedregexp,代码行数:23,代码来源:typedregexp.go

示例15: validateType

// validateType guarantees that the value is valid and assignable to the type.
func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
	if !value.IsValid() {
		if typ == nil || canBeNil(typ) {
			// An untyped nil interface{}. Accept as a proper nil value.
			return reflect.Zero(typ)
		}
		s.errorf("invalid value; expected %s", typ)
	}
	if typ != nil && !value.Type().AssignableTo(typ) {
		if value.Kind() == reflect.Interface && !value.IsNil() {
			value = value.Elem()
			if value.Type().AssignableTo(typ) {
				return value
			}
			// fallthrough
		}
		// Does one dereference or indirection work? We could do more, as we
		// do with method receivers, but that gets messy and method receivers
		// are much more constrained, so it makes more sense there than here.
		// Besides, one is almost always all you need.
		switch {
		case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
			value = value.Elem()
			if !value.IsValid() {
				s.errorf("dereference of nil pointer of type %s", typ)
			}
		case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
			value = value.Addr()
		default:
			s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
		}
	}
	return value
}
开发者ID:bibbyflyaway,项目名称:go,代码行数:35,代码来源:exec.go


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