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


Golang reflect.ValueOf函数代码示例

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


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

示例1: parseFloat

func parseFloat(value string) (reflect.Value, error) {
	b, err := strconv.ParseFloat(value, 64)
	if err != nil {
		return reflect.ValueOf(nil), conversionError(value, "float64")
	}
	return reflect.ValueOf(b), nil
}
开发者ID:TuneDB,项目名称:env,代码行数:7,代码来源:var.go

示例2: ObjectsAreEqual

// ObjectsAreEqual determines if two objects are considered equal.
//
// This function does no assertion of any kind.
func ObjectsAreEqual(expected, actual interface{}) bool {

	if expected == nil || actual == nil {
		return expected == actual
	}

	if reflect.DeepEqual(expected, actual) {
		return true
	}

	expectedValue := reflect.ValueOf(expected)
	actualValue := reflect.ValueOf(actual)
	if expectedValue == actualValue {
		return true
	}

	// Attempt comparison after type conversion
	if actualValue.Type().ConvertibleTo(expectedValue.Type()) && expectedValue == actualValue.Convert(expectedValue.Type()) {
		return true
	}

	// Last ditch effort
	if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) {
		return true
	}

	return false

}
开发者ID:2722,项目名称:lantern,代码行数:32,代码来源:assertions.go

示例3: CopyDataLine

func (t *Table) CopyDataLine(dims cube.Dimensions, aggs cube.Aggregates) string {
	ints := make([]interface{}, 0, len(t.aggcols)+len(t.dimcols))

	vDims := reflect.ValueOf(dims)
	vAggs := reflect.ValueOf(aggs)

	i := 0
	visitor := func(fieldValue reflect.Value, fieldDescription reflect.StructField) {
		ints = append(ints, t.dimcols[i].PrintInterface(fieldValue.Interface()))
		i += 1
	}
	VisitDimensions(vDims, visitor)

	j := 0
	visitorAgg := func(fieldValue reflect.Value, fieldDescription reflect.StructField) {
		ints = append(ints, t.aggcols[j].PrintInterface(fieldValue.Elem().Interface()))
		j += 1
	}

	VisitAggregates(vAggs, visitorAgg)
	/*
			for _, col := range t.dimcols {
				ints = append(ints, col.PrintInterface(vDims.Field(col.Index()).Interface()))
			}
		for _, col := range t.aggcols {
			ints = append(ints, col.PrintInterface(vAggs.Field(col.Index()).Elem().Interface()))
		}*/

	fs := t.getCopyDataLineFormatString()
	return fmt.Sprintf(fs, ints...)
}
开发者ID:adriansoghoian,项目名称:go-stream,代码行数:31,代码来源:table.go

示例4: Mod

func Mod(a, b interface{}) (int64, error) {
	av := reflect.ValueOf(a)
	bv := reflect.ValueOf(b)
	var ai, bi int64

	switch av.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		ai = av.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	switch bv.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		bi = bv.Int()
	default:
		return 0, errors.New("Modulo operator can't be used with non integer value")
	}

	if bi == 0 {
		return 0, errors.New("The number can't be divided by zero at modulo operation")
	}

	return ai % bi, nil
}
开发者ID:iswarezwp,项目名称:hugo,代码行数:25,代码来源:template_funcs.go

示例5: Exec

// Exec executes the statement represented by the InsertBuilder
// It returns the raw database/sql Result and an error if there was one.
// Regarding LastInsertID(): If you insert multiple rows using a single
// INSERT statement, LAST_INSERT_ID() returns the value generated for
// the first inserted row only. The reason for this is to make it possible to
// reproduce easily the same INSERT statement against some other server.
func (b *InsertBuilder) Exec() (sql.Result, error) {
	sql, args := b.ToSql()

	fullSql, err := Preprocess(sql, args)
	if err != nil {
		return nil, b.EventErrKv("dbr.insert.exec.interpolate", err, kvs{"sql": sql, "args": fmt.Sprint(args)})
	}

	// Start the timer:
	startTime := time.Now()
	defer func() { b.TimingKv("dbr.insert", time.Since(startTime).Nanoseconds(), kvs{"sql": fullSql}) }()

	result, err := b.runner.Exec(fullSql)
	if err != nil {
		return result, b.EventErrKv("dbr.insert.exec.exec", err, kvs{"sql": fullSql})
	}

	// If the structure has an "Id" field which is an int64, set it from the LastInsertId(). Otherwise, don't bother.
	if len(b.Recs) == 1 {
		rec := b.Recs[0]
		val := reflect.Indirect(reflect.ValueOf(rec))
		if val.Kind() == reflect.Struct && val.CanSet() {
			// @todo important: make Id configurable to match all magento internal ID columns
			if idField := val.FieldByName("Id"); idField.IsValid() && idField.Kind() == reflect.Int64 {
				if lastID, err := result.LastInsertId(); err == nil {
					idField.Set(reflect.ValueOf(lastID))
				} else {
					b.EventErrKv("dbr.insert.exec.last_inserted_id", err, kvs{"sql": fullSql})
				}
			}
		}
	}

	return result, nil
}
开发者ID:hafeez3000,项目名称:csfw,代码行数:41,代码来源:insert.go

示例6: Union

// Union outputs a collection that holds unique values of in and values collections
func Union(in Collection, values Collection, out Pointer) error {

	if !IsCollection(in) {
		return NotACollection("Value %v is not a collection", in)
	}
	if !IsCollection(values) {
		return NotACollection("Value %v is not a collection", values)
	}
	if !IsPointer(out) {
		return NotPointer("Value %v is not a pointer", out)
	}
	inVal := reflect.ValueOf(in)
	valuesVal := reflect.ValueOf(values)
	outVal := reflect.ValueOf(out)
	if a, b := inVal.Type(), valuesVal.Type(); a != b {
		return NotAssignable("Collection of type '%v' doesn't match type  ", a, b)
	}
	if a, c := inVal.Type(), outVal.Elem().Type(); !a.AssignableTo(c) {
		return NotAssignable("Collection of type '%v' is not assignable to output of type '%v'", a, c)
	}
	for i := 0; i < valuesVal.Len(); i++ {
		inVal = reflect.Append(inVal, valuesVal.Index(i))
	}
	if err := Unique(inVal.Interface(), out); err != nil {
		return err
	}
	return nil
}
开发者ID:Mparaiso,项目名称:lodash-go,代码行数:29,代码来源:lo.go

示例7: ReturnWhenSet

func ReturnWhenSet(a, k interface{}) interface{} {
	av, isNil := indirect(reflect.ValueOf(a))
	if isNil {
		return ""
	}

	var avv reflect.Value
	switch av.Kind() {
	case reflect.Array, reflect.Slice:
		index, ok := k.(int)
		if ok && av.Len() > index {
			avv = av.Index(index)
		}
	case reflect.Map:
		kv := reflect.ValueOf(k)
		if kv.Type().AssignableTo(av.Type().Key()) {
			avv = av.MapIndex(kv)
		}
	}

	if avv.IsValid() {
		switch avv.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return avv.Int()
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			return avv.Uint()
		case reflect.Float32, reflect.Float64:
			return avv.Float()
		case reflect.String:
			return avv.String()
		}
	}

	return ""
}
开发者ID:iswarezwp,项目名称:hugo,代码行数:35,代码来源:template_funcs.go

示例8: invoke

func (mw *middlewareHandler) invoke(ctx reflect.Value, rw ResponseWriter, req *Request, next NextMiddlewareFunc) {
	if mw.Generic {
		mw.GenericMiddleware(rw, req, next)
	} else {
		mw.DynamicMiddleware.Call([]reflect.Value{ctx, reflect.ValueOf(rw), reflect.ValueOf(req), reflect.ValueOf(next)})
	}
}
开发者ID:ahjdzx,项目名称:dis,代码行数:7,代码来源:router_serve.go

示例9: fixHandlerSignature

// Beat the supplied handler into a uniform signature. panics if incompatible
// (may only happen when the wrapped fun is called)
func fixHandlerSignature(f interface{}) parametrizedHandler {
	// classic net/http.Hander implementors can easily be converted
	if httph, ok := f.(http.Handler); ok {
		return func(ctx *Context, args ...string) error {
			httph.ServeHTTP(ctx.Response, ctx.Request)
			return nil
		}
	}
	fv := reflect.ValueOf(f)
	var callf valuefun = callableValue(fv)
	if !requiresContext(fv.Type()) {
		callf = disregardFirstArg(callf)
	}
	// now callf definitely accepts a *Context as its first arg
	if !lastRetIsError(fv) {
		callf = addNilErrorReturn(callf)
	}
	// now callf definitely returns an error as its last value
	if firstRetIsNonError(fv) {
		callf = writeFirstRetToFirstArg(callf)
	}
	// now callf definitely does not return its data: just an error
	// wrap callf in a function with pretty signature
	return func(ctx *Context, args ...string) error {
		argvs := make([]reflect.Value, len(args)+1)
		argvs[0] = reflect.ValueOf(ctx)
		for i, arg := range args {
			argvs[i+1] = reflect.ValueOf(arg)
		}
		rets := callf(argvs)
		return value2error(rets[0])
	}
}
开发者ID:xyproto,项目名称:web,代码行数:35,代码来源:handlerf.go

示例10: TestReflection

func TestReflection(t *testing.T) {
	o := js.Global.Call("eval", "({ answer: 42 })")
	if reflect.ValueOf(o).Interface().(*js.Object) != o {
		t.Fail()
	}

	type S struct {
		Field *js.Object
	}
	s := S{o}

	v := reflect.ValueOf(&s).Elem()
	if v.Field(0).Interface().(*js.Object).Get("answer").Int() != 42 {
		t.Fail()
	}
	if v.Field(0).MethodByName("Get").Call([]reflect.Value{reflect.ValueOf("answer")})[0].Interface().(*js.Object).Int() != 42 {
		t.Fail()
	}
	v.Field(0).Set(reflect.ValueOf(js.Global.Call("eval", "({ answer: 100 })")))
	if s.Field.Get("answer").Int() != 100 {
		t.Fail()
	}

	if fmt.Sprintf("%+v", s) != "{Field:[object Object]}" {
		t.Fail()
	}
}
开发者ID:apihooks,项目名称:aredis,代码行数:27,代码来源:js_test.go

示例11: valueOf

func (context *Context) valueOf(valuer func(interface{}, *qor.Context) interface{}, value interface{}, meta *Meta) interface{} {
	if valuer != nil {
		reflectValue := reflect.ValueOf(value)
		if reflectValue.Kind() != reflect.Ptr {
			reflectPtr := reflect.New(reflectValue.Type())
			reflectPtr.Elem().Set(reflectValue)
			value = reflectPtr.Interface()
		}

		result := valuer(value, context.Context)

		if reflectValue := reflect.ValueOf(result); reflectValue.IsValid() {
			if reflectValue.Kind() == reflect.Ptr {
				if reflectValue.IsNil() || !reflectValue.Elem().IsValid() {
					return nil
				}

				result = reflectValue.Elem().Interface()
			}

			if meta.Type == "number" || meta.Type == "float" {
				if context.isNewRecord(value) && equal(reflect.Zero(reflect.TypeOf(result)).Interface(), result) {
					return nil
				}
			}
			return result
		} else {
			return nil
		}
	}

	utils.ExitWithMsg(fmt.Sprintf("No valuer found for meta %v of resource %v", meta.Name, meta.baseResource.Name))
	return nil
}
开发者ID:musicking,项目名称:qor,代码行数:34,代码来源:func_map.go

示例12: lt

// lt evaluates the comparison a < b.
func lt(arg1, arg2 interface{}) (bool, error) {
	v1 := reflect.ValueOf(arg1)
	k1, err := basicKind(v1)
	if err != nil {
		return false, err
	}
	v2 := reflect.ValueOf(arg2)
	k2, err := basicKind(v2)
	if err != nil {
		return false, err
	}
	if k1 != k2 {
		return false, errBadComparison
	}
	truth := false
	switch k1 {
	case boolKind, complexKind:
		return false, errBadComparisonType
	case floatKind:
		truth = v1.Float() < v2.Float()
	case intKind:
		truth = v1.Int() < v2.Int()
	case stringKind:
		truth = v1.String() < v2.String()
	case uintKind:
		truth = v1.Uint() < v2.Uint()
	default:
		panic("invalid kind")
	}
	return truth, nil
}
开发者ID:horryq,项目名称:beego,代码行数:32,代码来源:templatefunc.go

示例13: RPC2XML

func RPC2XML(value interface{}) (string, error) {
	out := "<value>"
	switch reflect.ValueOf(value).Kind() {
	case reflect.Int:
		out += fmt.Sprintf("<int>%d</int>", value.(int))
	case reflect.Float64:
		out += fmt.Sprintf("<double>%f</double>", value.(float64))
	case reflect.String:
		out += String2XML(value.(string))
	case reflect.Bool:
		out += Bool2XML(value.(bool))
	case reflect.Struct:
		if reflect.TypeOf(value).String() != "time.Time" {
			out += Struct2XML(value)
		} else {
			out += Time2XML(value.(time.Time))
		}
	case reflect.Slice, reflect.Array:
		// FIXME: is it the best way to recognize '[]byte'?
		if reflect.TypeOf(value).String() != "[]uint8" {
			out += Array2XML(value)
		} else {
			out += Base642XML(value.([]byte))
		}
	case reflect.Ptr:
		if reflect.ValueOf(value).IsNil() {
			out += "<nil/>"
		}
	}
	out += "</value>"
	return out, nil
}
开发者ID:kzjeef,项目名称:gorilla-xmlrpc,代码行数:32,代码来源:rpc2xml.go

示例14: NewVarWithFunc

// NewVarWithFunc returns a new Var. get returns the value for the given key
func NewVarWithFunc(field reflect.StructField, get func(string) string) (*Var, error) {
	newVar := &Var{}
	newVar.Parse(field)

	value, err := convert(newVar.Type, get(newVar.Key), newVar.Decode)
	if err != nil {
		return newVar, err
	}
	newVar.SetValue(value)

	if value == reflect.ValueOf(nil) {
		if newVar.Required {
			return newVar, fmt.Errorf("%s required", newVar.Key)
		}

		// Check if we have a default value to set, otherwise set the type's zero value
		if newVar.Default != reflect.ValueOf(nil) {
			newVar.SetValue(newVar.Default)
		} else {
			newVar.SetValue(reflect.Zero(newVar.Type))
		}
	}

	if len(newVar.Options) > 0 {
		if !newVar.optionsContains(newVar.Value) {
			return newVar, fmt.Errorf(`%v="%v" not in allowed options: %v`, newVar.Key, newVar.Value, newVar.Options)
		}
	}

	return newVar, nil
}
开发者ID:TuneDB,项目名称:env,代码行数:32,代码来源:var.go

示例15: main

func main() {
	var x float64 = 6.54
	v := reflect.ValueOf(x)
	fmt.Println("type:", reflect.TypeOf(x))
	fmt.Println("value:", reflect.ValueOf(x))
	fmt.Println("kind is float64:", v.Kind() == reflect.String)
}
开发者ID:rwuebker,项目名称:go-practice,代码行数:7,代码来源:reflect.go


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