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


Golang reflect.TypeOf函数代码示例

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


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

示例1: testExpectedMRet

// testExpectedMRet is a convenience method to test an expected number of bytes
// written and error for a marshal.
func testExpectedMRet(t *testing.T, name string, n, wantN int, err, wantErr error) bool {
	// First ensure the number of bytes written is the expected value.  The
	// bytes read should be accurate even when an error occurs.
	if n != wantN {
		t.Errorf("%s: unexpected num bytes written - got: %v want: %v\n",
			name, n, wantN)
		return false
	}

	// Next check for the expected error.
	if reflect.TypeOf(err) != reflect.TypeOf(wantErr) {
		t.Errorf("%s: failed to detect error - got: %v <%[2]T> want: %T",
			name, err, wantErr)
		return false
	}
	if rerr, ok := err.(*MarshalError); ok {
		if werr, ok := wantErr.(*MarshalError); ok {
			if rerr.ErrorCode != werr.ErrorCode {
				t.Errorf("%s: failed to detect error code - "+
					"got: %v want: %v", name,
					rerr.ErrorCode, werr.ErrorCode)
				return false
			}
		}
	}

	return true
}
开发者ID:rasky,项目名称:go-xdr,代码行数:30,代码来源:encode_test.go

示例2: ToIntSliceE

// ToIntSliceE casts an empty interface to a []int.
func ToIntSliceE(i interface{}) ([]int, error) {
	jww.DEBUG.Println("ToIntSliceE called on type:", reflect.TypeOf(i))

	if i == nil {
		return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
	}

	switch v := i.(type) {
	case []int:
		return v, nil
	}

	kind := reflect.TypeOf(i).Kind()
	switch kind {
	case reflect.Slice, reflect.Array:
		s := reflect.ValueOf(i)
		a := make([]int, s.Len())
		for j := 0; j < s.Len(); j++ {
			val, err := ToIntE(s.Index(j).Interface())
			if err != nil {
				return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
			}
			a[j] = val
		}
		return a, nil
	default:
		return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
	}
}
开发者ID:BenoitHanotte,项目名称:shorturls,代码行数:30,代码来源:caste.go

示例3: init

func init() {
	mt := reflect.TypeOf(mail.Message{})
	ot := reflect.TypeOf(Message{})
	if mt.NumField() != ot.NumField() {
		panic(fmt.Errorf("mismatched number of fields %s v %s", mt, ot))
	}

	for i := 0; i < mt.NumField(); i++ {
		mf := mt.Field(i)
		of := mt.Field(i)
		if mf.Name != of.Name {
			panic(fmt.Errorf("mismatched names %s v %s", mf.Name, of.Name))
		}
		if mf.Name == "Attachments" {
			if !mf.Type.Elem().ConvertibleTo(of.Type.Elem()) {
				panic(fmt.Errorf("mismatched element type for Attachments %s v %s",
					mf.Type, of.Type))
			}
		} else {
			if mf.Type != of.Type {
				panic(fmt.Errorf("mismatched type for field %s: %s v %s", mf.Name, mf.Type, of.Type))
			}
		}
	}
}
开发者ID:nishanths,项目名称:gae,代码行数:25,代码来源:message.go

示例4: ParseUrlValues

// ParseUrlValues parses url.Values into the s interface using
// the reflect package. It also checks for the form struct tags
// so they can be used as fieldnames instead of the variable
// names. It returns the error if parsing failed.
func ParseUrlValues(query url.Values, s interface{}) error {
	fieldIndex := []int{0}
	numElements := reflect.TypeOf(s).Elem().NumField()
	for i := 0; i < numElements; i++ {
		fieldIndex[0] = i
		f := reflect.TypeOf(s).Elem().FieldByIndex(fieldIndex)
		v := reflect.ValueOf(s).Elem().FieldByIndex(fieldIndex)

		fieldname := f.Tag.Get("form")
		if fieldname == "" {
			fieldname = strings.ToLower(f.Name)
		}

		if val, ok := query[fieldname]; ok {
			curVal := val[0]
			switch v.Kind() {
			case reflect.Bool:
				castBool, _ := strconv.ParseBool(curVal)
				v.SetBool(castBool)
			case reflect.Float64:
				castFloat, _ := strconv.ParseFloat(curVal, 64)
				v.SetFloat(castFloat)
			case reflect.Int64:
				castInt, _ := strconv.ParseInt(curVal, 0, 64)
				v.SetInt(castInt)
			case reflect.String:
				v.SetString(curVal)
			default:
			}
		}
	}
	return nil
}
开发者ID:newestindustry,项目名称:go-form,代码行数:37,代码来源:request.go

示例5: SetExtension

// SetExtension sets the specified extension of pb to the specified value.
func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
	epb, ok := extendable(pb)
	if !ok {
		return errors.New("proto: not an extendable proto")
	}
	if err := checkExtensionTypes(epb, extension); err != nil {
		return err
	}
	typ := reflect.TypeOf(extension.ExtensionType)
	if typ != reflect.TypeOf(value) {
		return errors.New("proto: bad extension value type")
	}
	// nil extension values need to be caught early, because the
	// encoder can't distinguish an ErrNil due to a nil extension
	// from an ErrNil due to a missing field. Extensions are
	// always optional, so the encoder would just swallow the error
	// and drop all the extensions from the encoded message.
	if reflect.ValueOf(value).IsNil() {
		return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
	}

	extmap := epb.extensionsWrite()
	extmap[extension.Field] = Extension{desc: extension, value: value}
	return nil
}
开发者ID:7imon7ays,项目名称:bubblz,代码行数:26,代码来源:extensions.go

示例6: DescribeObject

// DescribeObject implements ObjectDescriber and will attempt to print the provided object to a string,
// if at least one describer function has been registered with the exact types passed, or if any
// describer can print the exact object in its first argument (the remainder will be provided empty
// values). If no function registered with Add can satisfy the passed objects, an ErrNoDescriber will
// be returned
// TODO: reorder and partial match extra.
func (d *Describers) DescribeObject(exact interface{}, extra ...interface{}) (string, error) {
	exactType := reflect.TypeOf(exact)
	fns, ok := d.searchFns[exactType]
	if !ok {
		return "", newErrNoDescriber(exactType)
	}
	if len(extra) == 0 {
		for _, typeFn := range fns {
			if len(typeFn.Extra) == 0 {
				return typeFn.Describe(exact, extra...)
			}
		}
		typeFn := fns[0]
		for _, t := range typeFn.Extra {
			v := reflect.New(t).Elem()
			extra = append(extra, v.Interface())
		}
		return fns[0].Describe(exact, extra...)
	}

	types := []reflect.Type{}
	for _, obj := range extra {
		types = append(types, reflect.TypeOf(obj))
	}
	for _, typeFn := range fns {
		if typeFn.Matches(types) {
			return typeFn.Describe(exact, extra...)
		}
	}
	return "", newErrNoDescriber(append([]reflect.Type{exactType}, types...)...)
}
开发者ID:duncanfinney,项目名称:kubernetes,代码行数:37,代码来源:describe.go

示例7: roundTrip

func roundTrip(t *testing.T, codec runtime.Codec, item runtime.Object) {
	//t.Logf("codec: %#v", codec)

	printer := spew.ConfigState{DisableMethods: true}

	name := reflect.TypeOf(item).Elem().Name()
	data, err := runtime.Encode(codec, item)
	if err != nil {
		t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", item))
		return
	}

	obj2, err := runtime.Decode(codec, data)
	if err != nil {
		t.Errorf("0: %v: %v\nCodec: %v\nData: %s\nSource: %#v", name, err, codec, string(data), printer.Sprintf("%#v", item))
		return
	}
	if !api.Semantic.DeepEqual(item, obj2) {
		t.Errorf("\n1: %v: diff: %v\nCodec: %v\nSource:\n\n%#v\n\nEncoded:\n\n%s\n\nFinal:\n\n%#v", name, diff.ObjectGoPrintDiff(item, obj2), codec, printer.Sprintf("%#v", item), string(data), printer.Sprintf("%#v", obj2))
		return
	}

	obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
	if err := runtime.DecodeInto(codec, data, obj3); err != nil {
		t.Errorf("2: %v: %v", name, err)
		return
	}
	if !api.Semantic.DeepEqual(item, obj3) {
		t.Errorf("3: %v: diff: %v\nCodec: %v", name, diff.ObjectDiff(item, obj3), codec)
		return
	}
}
开发者ID:xiaohui,项目名称:kubernetes,代码行数:32,代码来源:serialization_test.go

示例8: call

// Performs a request/response call for when the message is not NoWait and is
// specified as Synchronous.
func (me *Channel) call(req message, res ...message) error {
	if err := me.send(me, req); err != nil {
		return err
	}

	if req.wait() {
		select {
		case e := <-me.errors:
			return e

		case msg := <-me.rpc:
			if msg != nil {
				for _, try := range res {
					if reflect.TypeOf(msg) == reflect.TypeOf(try) {
						// *res = *msg
						vres := reflect.ValueOf(try).Elem()
						vmsg := reflect.ValueOf(msg).Elem()
						vres.Set(vmsg)
						return nil
					}
				}
				return ErrCommandInvalid
			} else {
				// RPC channel has been closed without an error, likely due to a hard
				// error on the Connection.  This indicates we have already been
				// shutdown and if were waiting, will have returned from the errors chan.
				return ErrClosed
			}
		}
	}

	return nil
}
开发者ID:gcnonato,项目名称:amqp,代码行数:35,代码来源:channel.go

示例9: coerce

func coerce(a, b interface{}) (x, y interface{}) {
	if reflect.TypeOf(a) == reflect.TypeOf(b) {
		return a, b
	}

	switch a.(type) {
	case idealComplex, idealFloat, idealInt, idealRune, idealUint:
		switch b.(type) {
		case idealComplex, idealFloat, idealInt, idealRune, idealUint:
			x, y = coerce1(a, b), b
			if reflect.TypeOf(x) == reflect.TypeOf(y) {
				return
			}

			return a, coerce1(b, a)
		default:
			return coerce1(a, b), b
		}
	default:
		switch b.(type) {
		case idealComplex, idealFloat, idealInt, idealRune, idealUint:
			return a, coerce1(b, a)
		default:
			return a, b
		}
	}
}
开发者ID:rwcarlsen,项目名称:ql,代码行数:27,代码来源:coerce.go

示例10: mixedTypeCompare

// Temporary workaround for #3633, allowing comparisons between
// heterogeneous types.
// TODO(andreimatei) Remove when type inference improves.
func mixedTypeCompare(l, r Datum) (int, bool) {
	lType := reflect.TypeOf(l)
	rType := reflect.TypeOf(r)

	// Check equality.
	eqOp, ok := CmpOps[CmpArgs{EQ, lType, rType}]
	if !ok {
		return 0, false
	}
	eq, err := eqOp.fn(EvalContext{}, l, r)
	if err != nil {
		panic(err)
	}
	if eq {
		return 0, true
	}

	// Check less than.
	ltOp, ok := CmpOps[CmpArgs{LT, lType, rType}]
	if !ok {
		return 0, false
	}
	lt, err := ltOp.fn(EvalContext{}, l, r)
	if err != nil {
		panic(err)
	}
	if lt {
		return -1, true
	}
	return 1, true
}
开发者ID:petermattis,项目名称:cockroach,代码行数:34,代码来源:datum.go

示例11: getKeyForField

//experimenting with trying to match the field with the passed in struct
func (v *Validation) getKeyForField(passedField interface{}) string {
	typObj := reflect.TypeOf(v.Obj)
	valObj := reflect.ValueOf(v.Obj)

	typField := reflect.TypeOf(passedField)
	valField := reflect.ValueOf(passedField)

	//if our struct is a pointer, dereference it
	if typObj.Kind() == reflect.Ptr {
		typObj = typObj.Elem()
		valObj = valObj.Elem()
	}

	//if our passed in field is a pointer, dereference it
	if typField.Kind() == reflect.Ptr {
		typField = typField.Elem()
		valField = valField.Elem()
	}

	for i := 0; i < typObj.NumField(); i++ {
		field := typObj.Field(i)
		fieldValue := valObj.Field(i).Interface()
		passedValue := valField.Interface()
		if passedValue == fieldValue {
			return field.Tag.Get(v.keyTag)
		}
	}
	return ""
}
开发者ID:Alpa-vantage,项目名称:fishhub,代码行数:30,代码来源:validation.go

示例12: TestVersionToto

func TestVersionToto(t *testing.T) {
	var datas = []struct {
		data   []byte
		result error
	}{
		{[]byte{0xFF}, &VersionError{}},
		{[]byte{0x02}, &VersionError{}},
		{[]byte{}, &ReadError{}},
		{[]byte{0x01}, &ReadError{}},
		{[]byte{0x01, 0xFF, 0x00, 0x0D, 0x00, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00}, &FunctionError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0D, 0x00, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00}, &ReadError{}},
		{[]byte{0x01, 0x01, 0x00, 0x0D, 0x00, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00}, &FunctionError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x02, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &FlagError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x00, 0x01, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &DialectError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &LanguageError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x00, 0x00, 'z', 'z', 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &LanguageError{}},
	}

	for _, infos := range datas {
		buf := bytes.NewReader(infos.data)
		p, err := GetPacket(buf)
		if err == nil {
			t.Errorf("Test failed, expected an error, got:  '%v'", p)
		}
		if reflect.TypeOf(err) != reflect.TypeOf(infos.result) {
			t.Errorf("Test failed, expected an %s, got:  '%s'", reflect.TypeOf(infos.result), err)
		}
		t.Logf("Got the error %s", err)
	}
}
开发者ID:SabatierBoris,项目名称:go-SLP,代码行数:30,代码来源:packetError_test.go

示例13: NewLink

// NewLink(n1, n2, [link1 properties, link2 properties])
// property which isn't specified will be generated
func NewLink(left, right Node, refs ...Link) Pair {
	result := Pair{}

	switch len(refs) {
	case 1:
		result = Pair{Left: refs[0], Right: Link{}}
	case 2:
		result = Pair{Left: refs[0], Right: refs[1]}
	default:
		break
	}

	if reflect.TypeOf(left).Elem() == reflect.TypeOf(right).Elem() && reflect.TypeOf(left).Elem() == reflect.TypeOf(Switch{}) {
		result.Left = result.Left.SetNodeName(left).SetName(left, "pp").SetPatch()
		result.Right = result.Right.SetNodeName(right).SetName(right, "pp").SetPatch()
	} else {
		result.Left = result.Left.SetCidr().SetHwAddr().
			SetNetNs(left).SetName(right, "eth").SetNodeName(left).SetState("DOWN").SetRoute()

		result.Right = result.Right.SetCidr().SetHwAddr().
			SetNetNs(right).SetName(right, "eth").SetNodeName(right).SetState("DOWN").SetRoute()
	}

	result.Left = result.Left.SetPeer(result.Right)
	result.Right = result.Right.SetPeer(result.Left)

	return result
}
开发者ID:NodePrime,项目名称:open-mininet,代码行数:30,代码来源:link.go

示例14: init

func init() {
	if err := content.RegisterType("net_paths", reflect.TypeOf([]string{})); err != nil {
		panic(err)
	} else if err := content.RegisterType("net_assemblies", reflect.TypeOf([]string{})); err != nil {
		panic(err)
	}
}
开发者ID:jerchung,项目名称:completion,代码行数:7,代码来源:net.go

示例15: main

func main() {
	file, err := os.OpenFile(
		"text01.txt",
		os.O_CREATE|os.O_RDWR|os.O_TRUNC, // 파일이 없으면 생성,
		// 읽기/쓰기, 파일을 연 뒤 내용 삭제
		os.FileMode(0644), // 파일 권한은 644
	)

	fmt.Println(reflect.TypeOf(file))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close() // main 함수가 끝나기 직전에 파일을 닫음

	w := bufio.NewWriter(file) // io.Writer 인터페이스를 따르는 file로
	// io.Writer 인터페이스를 따르는 쓰기 인스턴스 w 생성

	fmt.Println(reflect.TypeOf(w))

	w.WriteString("Hello, world!") // 쓰기 인스턴스로 버퍼에 Hello, world! 쓰기
	w.Flush()                      // 버퍼의 내용을 파일에 저장

	r := bufio.NewReader(file) // io.Reader 인터페이스를 따르는 file로
	// io.Reader 인터페이스를 따르는 읽기 인스턴스 r 생성
	fi, _ := file.Stat()         // 파일 정보 구하기
	b := make([]byte, fi.Size()) // 파일 크기만큼 바이트 슬라이스 생성

	file.Seek(0, os.SEEK_SET) // 파일 읽기 위치를 파일의 맨 처음(0)으로 이동
	r.Read(b)                 // 읽기 인스턴스로 파일의 내용을 읽어서 b에 저장

	fmt.Println(string(b)) // 문자열로 변환하여 b의 내용 출력
}
开发者ID:SimyungYang,项目名称:go-study,代码行数:33,代码来源:interface.go


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