當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。