本文整理汇总了Golang中reflect.Value.Type方法的典型用法代码示例。如果您正苦于以下问题:Golang Value.Type方法的具体用法?Golang Value.Type怎么用?Golang Value.Type使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reflect.Value
的用法示例。
在下文中一共展示了Value.Type方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: writeExtensions
// writeExtensions writes all the extensions in pv.
// pv is assumed to be a pointer to a protocol message struct that is extendable.
func writeExtensions(w *textWriter, pv reflect.Value) error {
emap := extensionMaps[pv.Type().Elem()]
ep := pv.Interface().(extendableProto)
// Order the extensions by ID.
// This isn't strictly necessary, but it will give us
// canonical output, which will also make testing easier.
var m map[int32]Extension
if em, ok := ep.(extensionsMap); ok {
m = em.ExtensionMap()
} else if em, ok := ep.(extensionsBytes); ok {
eb := em.GetExtensions()
var err error
m, err = BytesToExtensionsMap(*eb)
if err != nil {
return err
}
}
ids := make([]int32, 0, len(m))
for id := range m {
ids = append(ids, id)
}
sort.Sort(int32Slice(ids))
for _, extNum := range ids {
ext := m[extNum]
var desc *ExtensionDesc
if emap != nil {
desc = emap[extNum]
}
if desc == nil {
// Unknown extension.
if err := writeUnknownStruct(w, ext.enc); err != nil {
return err
}
continue
}
pb, err := GetExtension(ep, desc)
if err != nil {
return fmt.Errorf("failed getting extension: %v", err)
}
// Repeated extensions will appear as a slice.
if !desc.repeated() {
if err := writeExtension(w, desc.Name, pb); err != nil {
return err
}
} else {
v := reflect.ValueOf(pb)
for i := 0; i < v.Len(); i++ {
if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
return err
}
}
}
}
return nil
}
示例2: GetValQuoteStr
// for insert and update
// If already assigned, then just ignore tag
func GetValQuoteStr(val reflect.Value) (string, error) {
switch val.Kind() {
case reflect.Bool:
boolStr := "N"
if val.Bool() {
boolStr = "Y"
}
return boolStr, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(val.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(val.Uint(), 10), nil
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(val.Float(), 'f', -1, 64), nil
case reflect.String:
return QuoteStr(val.String()), nil
case reflect.Slice: //[]byte
if val.Type().Elem().Name() != "uint8" {
return "", fmt.Errorf("GetValQuoteStr> slicetype is not []byte: %v", val.Interface())
}
return QuoteStr(string(val.Interface().([]byte))), nil
default:
return "", fmt.Errorf("GetValQuoteStr> reflect.Value is not a string/int/uint/float/bool/[]byte!\nval: %v", val)
}
return "", nil
}
示例3: isZero
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.String:
return len(v.String()) == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Slice:
return v.Len() == 0
case reflect.Map:
return v.Len() == 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Struct:
vt := v.Type()
for i := v.NumField() - 1; i >= 0; i-- {
if vt.Field(i).PkgPath != "" {
continue // Private field
}
if !isZero(v.Field(i)) {
return false
}
}
return true
}
return false
}
示例4: ParseValue
func (par *parserParser) ParseValue(ctx *parseContext, valueOf reflect.Value, location int, err *Error) int {
var v Parser
if par.ptr {
v = valueOf.Addr().Interface().(Parser)
} else {
if valueOf.Kind() == reflect.Ptr {
valueOf = reflect.New(valueOf.Type().Elem())
}
v = valueOf.Interface().(Parser)
}
l, e := v.ParseValue(ctx.str, location)
if e != nil {
switch ev := e.(type) {
case Error:
err.Location = ev.Location
err.Message = ev.Message
err.Str = ev.Str
return -1
}
err.Location = location
err.Message = e.Error()
return -1
}
location = l
if location > len(ctx.str) {
panic("Invalid parser")
}
return location
}
示例5: validateStruct
// validateStruct will validate the struct value's fields. If the structure has
// nested types those types will be validated also.
func (v *validator) validateStruct(value reflect.Value, path string) {
prefix := "."
if path == "" {
prefix = ""
}
for i := 0; i < value.Type().NumField(); i++ {
f := value.Type().Field(i)
if strings.ToLower(f.Name[0:1]) == f.Name[0:1] {
continue
}
fvalue := value.FieldByName(f.Name)
notset := false
if f.Tag.Get("required") != "" {
switch fvalue.Kind() {
case reflect.Ptr, reflect.Slice, reflect.Map:
if fvalue.IsNil() {
notset = true
}
default:
if !fvalue.IsValid() {
notset = true
}
}
}
if notset {
msg := "missing required parameter: " + path + prefix + f.Name
v.errors = append(v.errors, msg)
} else {
v.validateAny(fvalue, path+prefix+f.Name)
}
}
}
示例6: SqlTag
func (d *commonDialect) SqlTag(value reflect.Value, size int) string {
switch value.Kind() {
case reflect.Bool:
return "BOOLEAN"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uintptr:
return "INTEGER"
case reflect.Int64, reflect.Uint64:
return "BIGINT"
case reflect.Float32, reflect.Float64:
return "FLOAT"
case reflect.String:
if size > 0 && size < 65532 {
return fmt.Sprintf("VARCHAR(%d)", size)
} else {
return "VARCHAR(65532)"
}
case reflect.Struct:
if value.Type() == timeType {
return "TIMESTAMP"
}
default:
if _, ok := value.Interface().([]byte); ok {
if size > 0 && size < 65532 {
return fmt.Sprintf("BINARY(%d)", size)
} else {
return "BINARY(65532)"
}
}
}
panic(fmt.Sprintf("invalid sql type %s (%s) for commonDialect", value.Type().Name(), value.Kind().String()))
}
示例7: printValue
// printValue is like printArg but starts with a reflect value, not an interface{} value.
func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
if !value.IsValid() {
if verb == 'T' || verb == 'v' {
p.buf.Write(nilAngleBytes)
} else {
p.badVerb(verb)
}
return false
}
// Special processing considerations.
// %T (the value's type) and %p (its address) are special; we always do them first.
switch verb {
case 'T':
p.printArg(value.Type().String(), 's', false, false, 0)
return false
case 'p':
p.fmtPointer(value, verb, goSyntax)
return false
}
// Handle values with special methods.
// Call always, even when arg == nil, because handleMethods clears p.fmt.plus for us.
p.arg = nil // Make sure it's cleared, for safety.
if value.CanInterface() {
p.arg = value.Interface()
}
if isString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
return isString
}
return p.printReflectValue(value, verb, plus, goSyntax, depth)
}
示例8: 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})
}
}
示例9: unmarshalLaxString
func (p *Decoder) unmarshalLaxString(s string, val reflect.Value) {
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i := mustParseInt(s, 10, 64)
val.SetInt(i)
return
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
i := mustParseUint(s, 10, 64)
val.SetUint(i)
return
case reflect.Float32, reflect.Float64:
f := mustParseFloat(s, 64)
val.SetFloat(f)
return
case reflect.Bool:
b := mustParseBool(s)
val.SetBool(b)
return
case reflect.Struct:
if val.Type() == timeType {
t, err := time.Parse(textPlistTimeLayout, s)
if err != nil {
panic(err)
}
val.Set(reflect.ValueOf(t.In(time.UTC)))
return
}
fallthrough
default:
panic(&incompatibleDecodeTypeError{val.Type(), String})
}
}
示例10: encode
func (e *Encoder) encode(v reflect.Value, dst map[string][]string) error {
var opts string
var value string
t := v.Type()
for i := 0; i < v.NumField(); i++ {
tag := t.Field(i).Tag.Get(e.TagID)
name := tag
if idx := strings.Index(tag, ","); idx != -1 {
name = tag[:idx]
opts = tag[idx+1:]
}
if name == "-" {
continue
}
encFunc, recurse := encoder(v.Field(i).Type())
if recurse {
e.encode(v.Field(i), dst)
continue
}
value = encFunc(v.Field(i))
if value == "" && strings.Contains(opts, "omitempty") {
continue
}
dst[name] = []string{value}
}
return nil
}
示例11: unmarshalArray
func (p *Decoder) unmarshalArray(pval *plistValue, val reflect.Value) {
subvalues := pval.value.([]*plistValue)
var n int
if val.Kind() == reflect.Slice {
// Slice of element values.
// Grow slice.
cnt := len(subvalues) + val.Len()
if cnt >= val.Cap() {
ncap := 2 * cnt
if ncap < 4 {
ncap = 4
}
new := reflect.MakeSlice(val.Type(), val.Len(), ncap)
reflect.Copy(new, val)
val.Set(new)
}
n = val.Len()
val.SetLen(cnt)
} else if val.Kind() == reflect.Array {
if len(subvalues) > val.Cap() {
panic(fmt.Errorf("plist: attempted to unmarshal %d values into an array of size %d", len(subvalues), val.Cap()))
}
} else {
panic(&incompatibleDecodeTypeError{val.Type(), pval.kind})
}
// Recur to read element into slice.
for _, sval := range subvalues {
p.unmarshal(sval, val.Index(n))
n++
}
return
}
示例12: parseScalar
func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error {
switch value := r.Interface().(type) {
case string:
v.Set(name, value)
case []byte:
if !r.IsNil() {
v.Set(name, base64.StdEncoding.EncodeToString(value))
}
case bool:
v.Set(name, strconv.FormatBool(value))
case int64:
v.Set(name, strconv.FormatInt(value, 10))
case int:
v.Set(name, strconv.Itoa(value))
case float64:
v.Set(name, strconv.FormatFloat(value, 'f', -1, 64))
case float32:
v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32))
case time.Time:
const ISO8601UTC = "2006-01-02T15:04:05Z"
v.Set(name, value.UTC().Format(ISO8601UTC))
default:
return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name())
}
return nil
}
示例13: setSliceFieldValue
func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue interface{}, data []string) error {
if len(data) == 0 && p.parameter.Required && p.parameter.Default == nil {
return errors.Required(p.Name, p.parameter.In)
}
defVal := reflect.Zero(target.Type())
if defaultValue != nil {
defVal = reflect.ValueOf(defaultValue)
}
if len(data) == 0 {
target.Set(defVal)
return nil
}
sz := len(data)
value := reflect.MakeSlice(reflect.SliceOf(target.Type().Elem()), sz, sz)
for i := 0; i < sz; i++ {
if err := p.setFieldValue(value.Index(i), nil, data[i]); err != nil {
return err
}
}
target.Set(value)
return nil
}
示例14: apply
// apply replaces each AST field x in val with f(x), returning val.
// To avoid extra conversions, f operates on the reflect.Value form.
func apply(f func(reflect.Value) reflect.Value, val reflect.Value) reflect.Value {
if !val.IsValid() {
return reflect.Value{}
}
// *ast.Objects introduce cycles and are likely incorrect after
// rewrite; don't follow them but replace with nil instead
if val.Type() == objectPtrType {
return objectPtrNil
}
// similarly for scopes: they are likely incorrect after a rewrite;
// replace them with nil
if val.Type() == scopePtrType {
return scopePtrNil
}
switch v := reflect.Indirect(val); v.Kind() {
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
e := v.Index(i)
setValue(e, f(e))
}
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
e := v.Field(i)
setValue(e, f(e))
}
case reflect.Interface:
e := v.Elem()
setValue(v, f(e))
}
return val
}
示例15: SqlTag
func (mssql) SqlTag(value reflect.Value, size int, autoIncrease bool) string {
switch value.Kind() {
case reflect.Bool:
return "bit"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uintptr:
if autoIncrease {
return "int IDENTITY(1,1)"
}
return "int"
case reflect.Int64, reflect.Uint64:
if autoIncrease {
return "bigint IDENTITY(1,1)"
}
return "bigint"
case reflect.Float32, reflect.Float64:
return "float"
case reflect.String:
if size > 0 && size < 65532 {
return fmt.Sprintf("nvarchar(%d)", size)
}
return "text"
case reflect.Struct:
if _, ok := value.Interface().(time.Time); ok {
return "datetime2"
}
default:
if _, ok := value.Interface().([]byte); ok {
if size > 0 && size < 65532 {
return fmt.Sprintf("varchar(%d)", size)
}
return "text"
}
}
panic(fmt.Sprintf("invalid sql type %s (%s) for mssql", value.Type().Name(), value.Kind().String()))
}