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


Golang reflect.Zero函数代码示例

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


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

示例1: bindFile

func bindFile(params *Params, name string, typ reflect.Type) reflect.Value {
	reader := getMultipartFile(params, name)
	if reader == nil {
		return reflect.Zero(typ)
	}

	// If it's already stored in a temp file, just return that.
	if osFile, ok := reader.(*os.File); ok {
		return reflect.ValueOf(osFile)
	}

	// Otherwise, have to store it.
	tmpFile, err := ioutil.TempFile("", "revel-upload")
	if err != nil {
		WARN.Println("Failed to create a temp file to store upload:", err)
		return reflect.Zero(typ)
	}

	// Register it to be deleted after the request is done.
	params.tmpFiles = append(params.tmpFiles, tmpFile)

	_, err = io.Copy(tmpFile, reader)
	if err != nil {
		WARN.Println("Failed to copy upload to temp file:", err)
		return reflect.Zero(typ)
	}

	_, err = tmpFile.Seek(0, 0)
	if err != nil {
		WARN.Println("Failed to seek to beginning of temp file:", err)
		return reflect.Zero(typ)
	}

	return reflect.ValueOf(tmpFile)
}
开发者ID:nolman,项目名称:revel,代码行数:35,代码来源:binder.go

示例2: getPrimaryKeys

func (association *Association) getPrimaryKeys(values ...interface{}) []interface{} {
	primaryKeys := []interface{}{}
	scope := association.Scope

	for _, value := range values {
		reflectValue := reflect.ValueOf(value)
		if reflectValue.Kind() == reflect.Ptr {
			reflectValue = reflectValue.Elem()
		}
		if reflectValue.Kind() == reflect.Slice {
			for i := 0; i < reflectValue.Len(); i++ {
				newScope := scope.New(reflectValue.Index(i).Interface())
				primaryKey := newScope.PrimaryKeyValue()
				if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) {
					primaryKeys = append(primaryKeys, primaryKey)
				}
			}
		} else if reflectValue.Kind() == reflect.Struct {
			newScope := scope.New(value)
			primaryKey := newScope.PrimaryKeyValue()
			if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) {
				primaryKeys = append(primaryKeys, primaryKey)
			}
		}
	}
	return primaryKeys
}
开发者ID:4honor,项目名称:obdi,代码行数:27,代码来源:association.go

示例3: zero

func zero(head P, mid string, typ reflect.Type) (value reflect.Value, err error) {
	switch typ.Kind() {

	case reflect.Ptr:
		value = reflect.New(typ.Elem())

	case reflect.Map:
		value = reflect.MakeMap(typ)

	case reflect.Slice:
		value = reflect.MakeSlice(typ, 0, 0)

	case reflect.Chan:
		value = reflect.MakeChan(typ, 1)

	case reflect.Func, reflect.Interface, reflect.UnsafePointer:
		value = reflect.Zero(typ)

	case reflect.Invalid:
		err = fmt.Errorf("unable to create '%s' at '%s'", typ, append(head, mid))

	default:
		value = reflect.Zero(typ)
	}

	return
}
开发者ID:nativetouch,项目名称:gopath,代码行数:27,代码来源:ensure.go

示例4: getPtrValues

// getPtrValues calls GetValue for each variable which has a proper (pointer) destination
func (cur *Cursor) getPtrValues() error {
	debug("getPtrValues %v %v", cur.bindVarsArr, cur.bindVarsMap)
	for _, v := range cur.bindVarsArr {
		if v.destination.IsValid() && !v.isArray {
			val, err := v.GetValue(0)
			debug("%s setting %v to %v %v", v, v.destination, val, err)
			if err != nil {
				return fmt.Errorf("error getting value of %s: %v", v, err)
			}
			if val == nil {
				v.destination.Elem().Set(reflect.Zero(v.destination.Elem().Type()))
			} else {
				v.destination.Elem().Set(reflect.ValueOf(val))
			}
		}
	}
	for k, v := range cur.bindVarsMap {
		if v.destination.IsValid() && !v.isArray {
			val, err := v.GetValue(0)
			debug("%s setting %v to %v %v", v, v.destination, val, err)
			if err != nil {
				return fmt.Errorf("error getting value of %s(%s): %v", k, v, err)
			}
			if val == nil {
				v.destination.Elem().Set(reflect.Zero(v.destination.Elem().Type()))
			} else {
				v.destination.Elem().Set(reflect.ValueOf(val))
			}
		}
	}
	return nil
}
开发者ID:tgulacsi,项目名称:go-sql-test,代码行数:33,代码来源:variable.go

示例5: decode

func (d *mapAsMapDecoder) decode(dv, sv reflect.Value) {
	dt := dv.Type()
	dv.Set(reflect.MakeMap(reflect.MapOf(dt.Key(), dt.Elem())))

	var mapKey reflect.Value
	var mapElem reflect.Value

	keyType := dv.Type().Key()
	elemType := dv.Type().Elem()

	for _, sElemKey := range sv.MapKeys() {
		var dElemKey reflect.Value
		var dElemVal reflect.Value

		if !mapKey.IsValid() {
			mapKey = reflect.New(keyType).Elem()
		} else {
			mapKey.Set(reflect.Zero(keyType))
		}
		dElemKey = mapKey

		if !mapElem.IsValid() {
			mapElem = reflect.New(elemType).Elem()
		} else {
			mapElem.Set(reflect.Zero(elemType))
		}
		dElemVal = mapElem

		d.keyDec(dElemKey, sElemKey)
		d.elemDec(dElemVal, sv.MapIndex(sElemKey))

		dv.SetMapIndex(dElemKey, dElemVal)
	}
}
开发者ID:kakamessi99,项目名称:shipyard,代码行数:34,代码来源:decoder_types.go

示例6: Prepare

func (ms *GobMarshaller) Prepare(name string, fn interface{}) (err error) {
	var (
		fT reflect.Type
	)
	// Gob needs to register type before encode/decode
	if fT = reflect.TypeOf(fn); fT.Kind() != reflect.Func {
		err = fmt.Errorf("fn is not a function but %v", fn)
		return
	}

	reg := func(v reflect.Value) (err error) {
		if !v.CanInterface() {
			err = fmt.Errorf("Can't convert to value in input of %v for name:%v", fn, name)
			return
		}

		gob.Register(v.Interface())
		return
	}

	for i := 0; i < fT.NumIn(); i++ {
		// create a zero value of the type of parameters
		if err = reg(reflect.Zero(fT.In(i))); err != nil {
			return
		}
	}

	for i := 0; i < fT.NumOut(); i++ {
		if err = reg(reflect.Zero(fT.Out(i))); err != nil {
			return
		}
	}

	return
}
开发者ID:MogeiWang,项目名称:dingo,代码行数:35,代码来源:marshaller_gob.go

示例7: dispatch

func dispatch(f interface{}, args ...interface{}) {
	fv := reflect.ValueOf(f)
	typ := fv.Type()
	numReq := typ.NumIn()
	numVals := numReq
	if typ.IsVariadic() {
		numReq-- // variadic can be []
		numVals--
		if len(args) > numReq {
			numVals = len(args)
		}
	}
	fargs := make([]reflect.Value, numVals)
	for i := 0; i < numVals; i++ {
		if i < len(args) {
			fargs[i] = reflect.ValueOf(args[i])
		} else if i >= numReq {
			// must be a variadic function
			fargs[i] = reflect.Zero(typ.In(numReq).Elem())
		} else {
			fargs[i] = reflect.Zero(typ.In(i))
		}
	}
	fv.Call(fargs)
}
开发者ID:kballard,项目名称:gocallback,代码行数:25,代码来源:callback.go

示例8: subtractStruct

// subtractStruct traverses a struct value and subtract each field
func subtractStruct(out, in1, in2 reflect.Value, ids map[int]bool) bool {
	if in1.NumField() != in2.NumField() {
		log.Fatalf("Tried to subtract two different struct types: %v vs %v", reflect.TypeOf(in1), reflect.TypeOf(in2))
	}

	changed := false
	for i := 0; i < in1.NumField()-1; i++ {
		// pointer to field i
		fieldPtrV1, fieldPtrV2 := in1.Field(i), in2.Field(i)
		if fieldPtrV1.IsNil() && fieldPtrV2.IsNil() {
			continue
		}
		// pointer to the change
		diffV := reflect.New(fieldPtrV1.Type().Elem())
		delta, isID := false, false
		if fieldPtrV1.IsNil() {
			// compare field value with zero value
			delta, isID = subtractValue(diffV.Elem(), reflect.Zero(fieldPtrV2.Elem().Type()), fieldPtrV2.Elem(), in2.String(), ids[i])
		} else if fieldPtrV2.IsNil() {
			// compare field value with zero value
			delta, isID = subtractValue(diffV.Elem(), fieldPtrV1.Elem(), reflect.Zero(fieldPtrV1.Elem().Type()), in1.String(), ids[i])
		} else {
			delta, isID = subtractValue(diffV.Elem(), fieldPtrV1.Elem(), fieldPtrV2.Elem(), in1.String(), ids[i])
		}
		if delta || isID {
			// only save the field in proto if there is a change or value serves as identifier
			out.Field(i).Set(diffV)
		}
		if delta {
			changed = true
		}
	}
	return changed
}
开发者ID:mike69d,项目名称:battery-historian,代码行数:35,代码来源:checkin_delta.go

示例9: Required

// Validates a struct, returning an error, and a list of field names if any fields tagged as validate:"required" are equal to zero based value.
func Required(i interface{}) (error, []string) {
	var err error
	t := reflect.TypeOf(i)
	err = errors.New("Error: " + t.Name() + " has required fields")
	infractions := []string{}
	ivalue := reflect.ValueOf(i)

	for index := 0; index < t.NumField(); index++ {
		field := t.Field(index)
		name := field.Name
		isValidate := field.Tag.Get(VALIDATE)

		// TODO will want to check what type of validation is happening. For now, only required is respected
		if isValidate != "" {
			switch ivalue.FieldByName(name).Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				if ivalue.FieldByName(name).Int() == reflect.Zero(field.Type).Int() {
					infractions = append(infractions, name)
				}
			case reflect.String:
				if ivalue.FieldByName(name).String() == reflect.Zero(field.Type).String() {
					infractions = append(infractions, name)
				}
			}
		}
	}

	if len(infractions) == 0 {
		err = nil
	}

	return err, infractions
}
开发者ID:zerocruft,项目名称:validate,代码行数:34,代码来源:required.go

示例10: call

func (c *Call) call(args []interface{}) (rets []interface{}, action func()) {
	c.numCalls++

	// Actions
	if c.doFunc.IsValid() {
		doArgs := make([]reflect.Value, len(args))
		ft := c.doFunc.Type()
		for i := 0; i < ft.NumIn(); i++ {
			if args[i] != nil {
				doArgs[i] = reflect.ValueOf(args[i])
			} else {
				// Use the zero value for the arg.
				doArgs[i] = reflect.Zero(ft.In(i))
			}
		}
		action = func() { c.doFunc.Call(doArgs) }
	}
	for n, v := range c.setArgs {
		reflect.ValueOf(args[n]).Elem().Set(v)
	}

	rets = c.rets
	if rets == nil {
		// Synthesize the zero value for each of the return args' types.
		mt := c.methodType()
		rets = make([]interface{}, mt.NumOut())
		for i := 0; i < mt.NumOut(); i++ {
			rets[i] = reflect.Zero(mt.Out(i)).Interface()
		}
	}

	return
}
开发者ID:Jyggafey,项目名称:drone,代码行数:33,代码来源:call.go

示例11: setValue

func setValue(dstVal reflect.Value, src interface{}) {
	if dstVal.Kind() == reflect.Ptr {
		dstVal = reflect.Indirect(dstVal)
	}
	srcVal := reflect.ValueOf(src)

	if !srcVal.IsValid() { // src is literal nil
		if dstVal.CanAddr() {
			// Convert to pointer so that pointer's value can be nil'ed
			//                     dstVal = dstVal.Addr()
		}
		dstVal.Set(reflect.Zero(dstVal.Type()))

	} else if srcVal.Kind() == reflect.Ptr {
		if srcVal.IsNil() {
			srcVal = reflect.Zero(dstVal.Type())
		} else {
			srcVal = reflect.ValueOf(src).Elem()
		}
		dstVal.Set(srcVal)
	} else {
		dstVal.Set(srcVal)
	}

}
开发者ID:kuenzaa,项目名称:rack,代码行数:25,代码来源:path_value.go

示例12: decodeValue

func (d *Decoder) decodeValue(rv reflect.Value, fn decFn) {
	d.d.initReadNext()

	if d.d.tryDecodeAsNil() {
		// If value in stream is nil, set the dereferenced value to its "zero" value (if settable)
		if rv.Kind() == reflect.Ptr {
			if !rv.IsNil() {
				rv.Set(reflect.Zero(rv.Type()))
			}
			return
		}
		// for rv.Kind() == reflect.Ptr {
		// 	rv = rv.Elem()
		// }
		if rv.IsValid() { // rv.CanSet() // always settable, except it's invalid
			rv.Set(reflect.Zero(rv.Type()))
		}
		return
	}

	// If stream is not containing a nil value, then we can deref to the base
	// non-pointer value, and decode into that.
	for rv.Kind() == reflect.Ptr {
		if rv.IsNil() {
			rv.Set(reflect.New(rv.Type().Elem()))
		}
		rv = rv.Elem()
	}

	if fn.i == nil {
		fn = d.getDecFn(rv.Type())
	}
	fn.f(fn.i, rv)
	return
}
开发者ID:nmenshov,项目名称:cocaine-framework-go,代码行数:35,代码来源:decode.go

示例13: FileConvert

func FileConvert(p *Params, n string, typ reflect.Type) reflect.Value {
	file := getMultipartFile(p, n)
	if file == nil {
		return reflect.Zero(typ)
	}
	if osFile, ok := file.(*os.File); ok {
		return reflect.ValueOf(osFile)
	}
	//store temp file
	osFile, err := ioutil.TempFile("", "peony-upload-file")
	if err != nil {
		WARN.Println("create temp file error,", err)
		return reflect.Zero(typ)
	}
	p.tmpFiles = append(p.tmpFiles, osFile)
	_, err = io.Copy(osFile, file)
	if err != nil {
		WARN.Println("save data to temp file error,", err)
		return reflect.Zero(typ)
	}
	_, err = osFile.Seek(0, 0)
	if err != nil {
		WARN.Println("seek to begin of temp file error,", err)
		return reflect.Zero(typ)
	}
	return reflect.ValueOf(osFile)
}
开发者ID:Joinhack,项目名称:peony,代码行数:27,代码来源:converter.go

示例14: 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

示例15: mapForm

// Takes values from the form data and puts them into a struct
func mapForm(formStruct reflect.Value, form map[string][]string,
	formfile map[string][]*multipart.FileHeader, errors Errors) {

	if formStruct.Kind() == reflect.Ptr {
		formStruct = formStruct.Elem()
	}
	typ := formStruct.Type()

	for i := 0; i < typ.NumField(); i++ {
		typeField := typ.Field(i)
		structField := formStruct.Field(i)

		if typeField.Type.Kind() == reflect.Ptr && typeField.Anonymous {
			structField.Set(reflect.New(typeField.Type.Elem()))
			mapForm(structField.Elem(), form, formfile, errors)
			if reflect.DeepEqual(structField.Elem().Interface(), reflect.Zero(structField.Elem().Type()).Interface()) {
				structField.Set(reflect.Zero(structField.Type()))
			}
		} else if typeField.Type.Kind() == reflect.Struct {
			mapForm(structField, form, formfile, errors)
		}

		inputFieldName := parseFormName(typeField.Name, typeField.Tag.Get("form"))
		if len(inputFieldName) == 0 || !structField.CanSet() {
			continue
		}

		inputValue, exists := form[inputFieldName]
		if exists {
			numElems := len(inputValue)
			if structField.Kind() == reflect.Slice && numElems > 0 {
				sliceOf := structField.Type().Elem().Kind()
				slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
				for i := 0; i < numElems; i++ {
					setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
				}
				formStruct.Field(i).Set(slice)
			} else {
				setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
			}
			continue
		}

		inputFile, exists := formfile[inputFieldName]
		if !exists {
			continue
		}
		fhType := reflect.TypeOf((*multipart.FileHeader)(nil))
		numElems := len(inputFile)
		if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType {
			slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
			for i := 0; i < numElems; i++ {
				slice.Index(i).Set(reflect.ValueOf(inputFile[i]))
			}
			structField.Set(slice)
		} else if structField.Type() == fhType {
			structField.Set(reflect.ValueOf(inputFile[0]))
		}
	}
}
开发者ID:Xetius,项目名称:grafana,代码行数:61,代码来源:binding.go


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