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


Golang Type.Len方法代码示例

本文整理汇总了Golang中reflect.Type.Len方法的典型用法代码示例。如果您正苦于以下问题:Golang Type.Len方法的具体用法?Golang Type.Len怎么用?Golang Type.Len使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在reflect.Type的用法示例。


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

示例1: arrayEncoder

func arrayEncoder(typ reflect.Type) (typeEncoder, error) {
	al := typ.Len()
	etyp := typ.Elem()
	switch etyp.Kind() {
	case reflect.Int8, reflect.Uint8, reflect.Int16, reflect.Uint16, reflect.Int32, reflect.Uint32, reflect.Int64, reflect.Uint64:
		// Take advantage of the fast path in Write
		return func(enc *encoder, p unsafe.Pointer) error {
			v := reflect.NewAt(typ, p).Elem().Slice(0, al)
			return Write(enc, enc.order, v.Interface())
		}, nil
	}
	eenc, err := makeEncoder(etyp)
	if err != nil {
		return nil, err
	}
	s := etyp.Size()
	return func(enc *encoder, p unsafe.Pointer) error {
		for ii := 0; ii < al; ii++ {
			if err := eenc(enc, p); err != nil {
				return err
			}
			p = unsafe.Pointer(uintptr(p) + s)
		}
		return nil
	}, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:26,代码来源:encoder_unsafe.go

示例2: decodeArray

func decodeArray(t reflect.Type) interface{} {
	slType := reflect.SliceOf(t.Elem())
	slDec := getTypeDecoder(slType)
	_, ok := slDec.(decodeFunc)
	l := t.Len()
	return decodeReflectFunc(func(dec *Decoder, v reflect.Value) error {
		p := v.UnsafeAddr()
		var err error
		if ok {
			slice := reflect.SliceHeader{
				Len: l, Cap: l,
				Data: p,
			}
			err = (slDec.(decodeFunc))(dec, unsafe.Pointer(&slice))
			if slice.Len != l {
				return ErrorIncorrectLength{l, slice.Len}
			}
		} else {
			slice := v.Slice(0, v.Len())
			ptr := reflect.New(slType)
			ptr.Elem().Set(slice)
			err = (slDec.(decodeReflectFunc))(dec, ptr.Elem())
			if slice.Len() != l {
				return ErrorIncorrectLength{l, slice.Len()}
			}
		}
		return err
	})
}
开发者ID:experimental-games,项目名称:netherrack,代码行数:29,代码来源:decoding.go

示例3: formFromGoType

// formFromGoType returns a suitable FITS TFORM string from a reflect.Type
func formFromGoType(rt reflect.Type, htype HDUType) string {
	hdr := ""
	var t reflect.Type
	switch rt.Kind() {
	case reflect.Array:
		hdr = fmt.Sprintf("%d", rt.Len())
		t = rt.Elem()
	case reflect.Slice:
		hdr = "Q"
		t = rt.Elem()
	default:
		t = rt
	}

	dict, ok := g_gotype2FITS[t.Kind()]
	if !ok {
		return ""
	}

	form, ok := dict[htype]
	if !ok {
		return ""
	}

	return hdr + form
}
开发者ID:ramvasanth,项目名称:fitsio,代码行数:27,代码来源:utils.go

示例4: sizeof

func sizeof(t reflect.Type) (int, error) {
	switch t.Kind() {
	case reflect.Array:
		n, err := sizeof(t.Elem())
		if err != nil {
			return 0, err
		}
		return t.Len() * n, nil

	case reflect.Struct:
		sum := 0
		for i, n := 0, t.NumField(); i < n; i++ {
			s, err := sizeof(t.Field(i).Type)
			if err != nil {
				return 0, err
			}
			sum += s
		}
		return sum, nil

	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
		reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
		return int(t.Size()), nil
	}
	return 0, errors.New("invalid type " + t.String())
}
开发者ID:h8liu,项目名称:golang,代码行数:27,代码来源:binary.go

示例5: sliceDecoder

func sliceDecoder(typ reflect.Type) (typeDecoder, error) {
	switch typ.Elem().Kind() {
	case reflect.Int8, reflect.Uint8, reflect.Int16, reflect.Uint16, reflect.Int32, reflect.Uint32, reflect.Int64, reflect.Uint64:
		// Take advantage of the fast path in Read
		if typ.Kind() == reflect.Slice {
			return func(dec *decoder, v reflect.Value) error {
				return Read(dec, dec.order, v.Interface())
			}, nil
		}
		// Array
		al := typ.Len()
		return func(dec *decoder, v reflect.Value) error {
			// Value must be addressable when we reach this point
			return Read(dec, dec.order, v.Slice(0, al).Interface())
		}, nil
	}
	edec, err := makeDecoder(typ.Elem())
	if err != nil {
		return nil, err
	}
	return func(dec *decoder, v reflect.Value) error {
		sl := v.Len()
		for ii := 0; ii < sl; ii++ {
			if err := edec(dec, v.Index(ii)); err != nil {
				return err
			}
		}
		return nil
	}, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:30,代码来源:decoder.go

示例6: sizeof

// sizeof returns the size >= 0 of variables for the given type or -1 if the type is not acceptable.
func sizeof(t reflect.Type) int {
	switch t.Kind() {
	case reflect.Array:
		if s := sizeof(t.Elem()); s >= 0 {
			return s * t.Len()
		}

	case reflect.Struct:
		sum := 0
		for i, n := 0, t.NumField(); i < n; i++ {
			s := sizeof(t.Field(i).Type)
			if s < 0 {
				return -1
			}
			sum += s
		}
		return sum

	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
		reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.Ptr:
		return int(t.Size())
	}

	return -1
}
开发者ID:freedomkk-qfeng,项目名称:agent,代码行数:27,代码来源:binary.go

示例7: evalCompositeLitArrayOrSlice

func evalCompositeLitArrayOrSlice(ctx *Ctx, t reflect.Type, lit *CompositeLit, env *Env) (*reflect.Value, bool, error) {

	v := reflect.New(t).Elem()

	var curKey uint64 = 0
	var size uint64 = 0
	if t.Kind() == reflect.Array {
		size = uint64(t.Len())
	} else {
		// Check all keys are valid and calculate slice size.
		// Elements with key are placed at the keyed position.
		// Elements without are placed one after the previous.
		// For example, []int{1, 2:1, 1} -> [1, 0, 1, 1]
		for _, elt := range lit.Elts {
			if kv, ok := elt.(*KeyValueExpr); !ok {
				size += 1
			} else if k, ok := kv.Key.(*BasicLit); !ok || k.Kind != token.INT {
				return nil, false, ErrArrayKey

				// The limit of 2^31 elements is infered from the go implementation
				// The actual limit is "largest value representable by an int"
			} else if i, err := strconv.ParseUint(k.Value, 0, 31); err != nil {
				return nil, false, ErrArrayKey
			} else if !(i < size) {
				size = i + 1
			}
		}
		// Allocate the slice
		v.Set(reflect.MakeSlice(t, int(size), int(size)))
	}

	// Fill the array or slice, the reflect interface is identical for both
	for _, elt := range lit.Elts {
		var expr ast.Expr
		if kv, ok := elt.(*KeyValueExpr); !ok {
			expr = elt
		} else {
			// We know this expression to be valid from above.
			curKey, _ = strconv.ParseUint(kv.Key.(*BasicLit).Value, 0, 31)
			expr = kv.Value
		}

		if !(curKey < size) {
			return nil, false, ErrArrayIndexOutOfBounds{t, curKey}
		}

		// Evaluate and set the element
		elem := v.Index(int(curKey))
		if values, typed, err := EvalExpr(ctx, expr.(Expr), env); err != nil {
			return nil, false, err
		} else if value, err := expectSingleValue(ctx, *values, elt); err != nil {
			return nil, false, err
		} else if err := setTypedValue(elem, value, typed); err != nil {
			return nil, false, err
		}
		curKey += 1
	}
	return &v, true, nil
}
开发者ID:raff,项目名称:eval,代码行数:59,代码来源:compositelitexpr.go

示例8: typeString

// Return the string that should be used to refer to the supplied type within
// the given package. The output is not guaranteed to be pretty, and should be
// run through a tool like gofmt afterward.
//
// For example, a pointer to an io.Reader may be rendered as "*Reader" or
// "*io.Reader" depending on whether the package path is "io" or not.
func typeString(
	t reflect.Type,
	pkgPath string) (s string) {
	// Is this type named? If so we use its name, possibly with a package prefix.
	//
	// Examples:
	//
	//     int
	//     string
	//     error
	//     gcs.Bucket
	//
	if t.Name() != "" {
		if t.PkgPath() == pkgPath {
			s = t.Name()
		} else {
			s = t.String()
		}

		return
	}

	// This type is unnamed. Recurse.
	switch t.Kind() {
	case reflect.Array:
		s = fmt.Sprintf("[%d]%s", t.Len(), typeString(t.Elem(), pkgPath))

	case reflect.Chan:
		s = fmt.Sprintf("%s %s", t.ChanDir(), typeString(t.Elem(), pkgPath))

	case reflect.Func:
		s = typeString_Func(t, pkgPath)

	case reflect.Interface:
		s = typeString_Interface(t, pkgPath)

	case reflect.Map:
		s = fmt.Sprintf(
			"map[%s]%s",
			typeString(t.Key(), pkgPath),
			typeString(t.Elem(), pkgPath))

	case reflect.Ptr:
		s = fmt.Sprintf("*%s", typeString(t.Elem(), pkgPath))

	case reflect.Slice:
		s = fmt.Sprintf("[]%s", typeString(t.Elem(), pkgPath))

	case reflect.Struct:
		s = typeString_Struct(t, pkgPath)

	default:
		log.Panicf("Unhandled kind %v for type: %v", t.Kind(), t)
	}

	return
}
开发者ID:chenqi123,项目名称:cq_tkbl_api,代码行数:63,代码来源:type_string.go

示例9: assignPrimitive

func (s *Shader) assignPrimitive(ptr unsafe.Pointer, typ reflect.Type, u gl.UniformLocation) bool {
	switch typ.Kind() {
	// basic primitives
	case reflect.Int:
		u.Uniform1i(*(*int)(ptr))
	case reflect.Int32:
		u.Uniform1i(int(*(*int32)(ptr)))
	case reflect.Float32:
		u.Uniform1f(*(*float32)(ptr))
	// arrays represent vectors or matrices
	case reflect.Array:
		size := typ.Len()
		elemtyp := typ.Elem()
		switch elemtyp.Kind() {
		case reflect.Int32:
			switch size {
			case 2:
				slice := (*(*[2]int32)(ptr))[:]
				u.Uniform2iv(1, slice)
			case 3:
				slice := (*(*[3]int32)(ptr))[:]
				u.Uniform3iv(1, slice)
			case 4:
				slice := (*(*[4]int32)(ptr))[:]
				u.Uniform4iv(1, slice)
			default:
				return false
			}
		case reflect.Float32:
			switch size {
			case 2:
				slice := (*(*[2]float32)(ptr))[:]
				u.Uniform2fv(1, slice)
			case 3:
				slice := (*(*[3]float32)(ptr))[:]
				u.Uniform3fv(1, slice)
			case 4:
				slice := (*(*[4]float32)(ptr))[:]
				u.Uniform4fv(1, slice)
			case 9:
				matptr := (*[9]float32)(ptr)
				u.UniformMatrix3f(false, matptr)
			case 16:
				matptr := (*[16]float32)(ptr)
				u.UniformMatrix4f(false, matptr)
			default:
				return false
			}
		default:
			return false
		}
	default:
		return false
	}
	return true
}
开发者ID:james4k,项目名称:gfx,代码行数:56,代码来源:shader.go

示例10: getArrayDims

func getArrayDims(dt reflect.Type) []int {
	result := []int{}
	if dt.Kind() == reflect.Array {
		result = append(result, dt.Len())
		for _, dim := range getArrayDims(dt.Elem()) {
			result = append(result, dim)
		}
	}
	return result
}
开发者ID:kisielk,项目名称:go-hdf5,代码行数:10,代码来源:h5t.go

示例11: reifyArray

func reifyArray(
	opts fieldOptions,
	to reflect.Value, tTo reflect.Type,
	val value,
) (reflect.Value, Error) {
	arr := castArr(val)
	if len(arr) != tTo.Len() {
		ctx := val.Context()
		return reflect.Value{}, raiseArraySize(ctx, val.meta(), len(arr), tTo.Len())
	}
	return reifyDoArray(opts, to, tTo.Elem(), val, arr)
}
开发者ID:McStork,项目名称:beats,代码行数:12,代码来源:reify.go

示例12: getKeyInfoByParent

//获取t对应的类型信息,不支持slice, function, map, pointer, interface, channel
//如果parentIdx的长度>0,则表示t是strut中的字段的类型信息, t为字段对应的类型
func getKeyInfoByParent(t reflect.Type, parent *keyInfo, parentIdx []int) (ki *keyInfo, err error) {
	ki = &keyInfo{}
	//判断是否实现了hasher接口
	if t.Implements(hasherT) {
		ki.isHasher = true
		return
	}
	ki.kind = t.Kind()

	if _, ok := engM[ki.kind]; ok {
		//简单类型,不需要再分解元素类型的信息
		ki.index = parentIdx
	} else {
		//some types can be used as key, we can use equals to test
		switch ki.kind {
		case reflect.Chan, reflect.Slice, reflect.Func, reflect.Map, reflect.Ptr, reflect.Interface:
			err = NonSupportKey
		case reflect.Struct:
			if parent == nil {
				//parent==nil表示t不是一个嵌套的struct,所以这里需要初始化fields
				parent = ki
				ki.fields = make([]*keyInfo, 0, t.NumField())
			}
			for i := 0; i < t.NumField(); i++ {
				f := t.Field(i)
				//skip unexported field,
				if len(f.PkgPath) > 0 {
					continue
				}

				idx := make([]int, len(parentIdx), len(parentIdx)+1)
				copy(idx, parentIdx)
				idx = append(idx, i)
				if fi, e := getKeyInfoByParent(f.Type, parent, idx); e != nil {
					err = e
					return
				} else {
					//fi.index = i
					parent.fields = append(ki.fields, fi)
				}
			}
		case reflect.Array:
			if ki.elementInfo, err = getKeyInfo(t.Elem()); err != nil {
				return
			}
			ki.size = t.Len()
			ki.index = parentIdx
		}
	}

	return

}
开发者ID:HearingFish,项目名称:go-concurrentMap,代码行数:55,代码来源:util.go

示例13: ValType

func ValType(t reflect.Type) (decl string) {
	switch k := t.Kind(); k {
	case reflect.Struct:
		decl = "struct {\n"
		for i, ed := 0, t.NumField(); i < ed; i++ {
			ft := t.Field(i)
			if ft.Tag != "-" || ft.Tag.Get("goval") == "-" {
				s := ft.Name + " " + ValType(ft.Type)
				if ft.Tag != "" {
					s += " `" + strings.Replace("`", "\\`", string(ft.Tag), -1) + "`"
				}
				decl += indent(s) + "\n"
			}
		}
		decl += "}"
	case reflect.Array:
		decl = "[" + strconv.Itoa(t.Len()) + "]" + Val(t.Elem())
	case reflect.Slice:
		decl = "[]" + Val(t.Elem())
	case reflect.Chan:
		switch t.ChanDir() {
		case reflect.RecvDir:
			decl = "<-chan "
		case reflect.SendDir:
			decl = "chan<- "
		case reflect.BothDir:
			decl = "chan "
		default:
			panic("Didn't expect a dir other than send, recieve or both.")
		}
		decl += Val(t.Elem())
	case reflect.Map:
		decl = "map[" + ValType(t.Key()) + "]" + ValType(t.Elem())
	case reflect.Ptr:
		decl = "*" + ValType(t.Elem())
	case reflect.Interface:
		decl = "interface {\n"
		for i, ed := 0, t.NumMethod(); i < ed; i++ {
			ft := t.Method(i)
			s := ft.Name + FormatFuncArguments(ft.Type)
			decl += indent(s) + "\n"
		}
		decl += "}"
	case reflect.Func:
		decl = "func" + FormatFuncArguments(t)
	default:
		return k.String()
	}

	return
}
开发者ID:TShadwell,项目名称:fweight,代码行数:51,代码来源:goval.go

示例14: sizeof

func sizeof(t reflect.Type) int {
	switch t := t.(type) {
	case *reflect.ArrayType:
		n := sizeof(t.Elem())
		if n < 0 {
			return -1
		}
		return t.Len() * n

	case *reflect.StructType:
		sum := 0
		for i, n := 0, t.NumField(); i < n; i++ {
			s := sizeof(t.Field(i).Type)
			if s < 0 {
				return -1
			}
			sum += s
		}
		return sum

	case *reflect.Uint8Type:
		return 1
	case *reflect.Uint16Type:
		return 2
	case *reflect.Uint32Type:
		return 4
	case *reflect.Uint64Type:
		return 8
	case *reflect.Int8Type:
		return 1
	case *reflect.Int16Type:
		return 2
	case *reflect.Int32Type:
		return 4
	case *reflect.Int64Type:
		return 8
	case *reflect.Float32Type:
		return 4
	case *reflect.Float64Type:
		return 8
	}
	return -1
}
开发者ID:edisonwsk,项目名称:golang-on-cygwin,代码行数:43,代码来源:binary.go

示例15: encodeArray

func encodeArray(t reflect.Type) interface{} {
	//Cheat by turning the array into a slice
	slEnc := getTypeEncoder(reflect.SliceOf(t.Elem()))
	l := t.Len()
	_, ok := slEnc.(encodeFunc)
	return encodeReflectFunc(func(enc *Encoder, v reflect.Value) error {
		if ok {
			slice := reflect.SliceHeader{ //Convert to slice
				Data: v.UnsafeAddr(),
				Len:  l,
				Cap:  l,
			}
			encF := slEnc.(encodeFunc)
			return encF(enc, unsafe.Pointer(&slice))
		} else {
			encF := slEnc.(encodeReflectFunc)
			return encF(enc, v.Slice(0, v.Len()))
		}
	})
}
开发者ID:experimental-games,项目名称:netherrack,代码行数:20,代码来源:encoding.go


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