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


Golang reflect.Indirect函数代码示例

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


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

示例1: ScanVals

//This will execute the SQL and append results to the slice.
//    var ids []uint32
//    if err := From("test").Select("id").ScanVals(&ids); err != nil{
//        panic(err.Error()
//    }
//
//i: Takes a pointer to a slice of primitive values.
func (me CrudExec) ScanVals(i interface{}) error {
	if me.err != nil {
		return me.err
	}
	val := reflect.ValueOf(i)
	if val.Kind() != reflect.Ptr {
		return NewGoquError("Type must be a pointer to a slice when calling ScanVals")
	}
	val = reflect.Indirect(val)
	if val.Kind() != reflect.Slice {
		return NewGoquError("Type must be a pointer to a slice when calling ScanVals")
	}
	t, _, isSliceOfPointers := getTypeInfo(i, val)
	rows, err := me.database.Query(me.Sql, me.Args...)
	if err != nil {
		return err
	}
	defer rows.Close()
	for rows.Next() {
		row := reflect.New(t)
		if err := rows.Scan(row.Interface()); err != nil {
			return err
		}
		if isSliceOfPointers {
			val.Set(reflect.Append(val, row))
		} else {
			val.Set(reflect.Append(val, reflect.Indirect(row)))
		}
	}
	if err := rows.Err(); err != nil {
		return err
	}
	return nil

}
开发者ID:aheuermann,项目名称:goqu,代码行数:42,代码来源:crud_exec.go

示例2: stringTypeOf

func stringTypeOf(i interface{}) (string, error) {
	_, isByteSlice := i.([]byte)
	if !isByteSlice {
		// Check if we found a higher kinded type
		switch reflect.ValueOf(i).Kind() {
		case reflect.Slice:
			elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface()
			ct := cassaType(elemVal)
			if ct == gocql.TypeCustom {
				return "", fmt.Errorf("Unsupported type %T", i)
			}
			return fmt.Sprintf("list<%v>", ct), nil
		case reflect.Map:
			keyVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Key())).Interface()
			elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface()
			keyCt := cassaType(keyVal)
			elemCt := cassaType(elemVal)
			if keyCt == gocql.TypeCustom || elemCt == gocql.TypeCustom {
				return "", fmt.Errorf("Unsupported map key or value type %T", i)
			}
			return fmt.Sprintf("map<%v, %v>", keyCt, elemCt), nil
		}
	}
	ct := cassaType(i)
	if ct == gocql.TypeCustom {
		return "", fmt.Errorf("Unsupported type %T", i)
	}
	return cassaTypeToString(ct)
}
开发者ID:torfuzx,项目名称:gocassa,代码行数:29,代码来源:generate.go

示例3: extractUnderlyingFd

/*
 * I also don't see that golang exports an API to get at the underlying FD, but
 * we need it to get at SO_PEERCRED, so let's grab it.
 */
func extractUnderlyingFd(unixConnPtr *net.UnixConn) int {
	conn := reflect.Indirect(reflect.ValueOf(unixConnPtr))
	netFdPtr := conn.FieldByName("fd")
	netFd := reflect.Indirect(netFdPtr)
	fd := netFd.FieldByName("sysfd")
	return int(fd.Int())
}
开发者ID:mickydelfavero,项目名称:lxd,代码行数:11,代码来源:devlxd.go

示例4: TestDataCustomTypes

func TestDataCustomTypes(t *testing.T) {
	d := DataCustom{}
	ind := reflect.Indirect(reflect.ValueOf(&d))

	for name, value := range Data_Values {
		e := ind.FieldByName(name)
		if !e.IsValid() {
			continue
		}
		e.Set(reflect.ValueOf(value).Convert(e.Type()))
	}

	id, err := dORM.Insert(&d)
	throwFail(t, err)
	throwFail(t, AssertIs(id, 1))

	d = DataCustom{Id: 1}
	err = dORM.Read(&d)
	throwFail(t, err)

	ind = reflect.Indirect(reflect.ValueOf(&d))

	for name, value := range Data_Values {
		e := ind.FieldByName(name)
		if !e.IsValid() {
			continue
		}
		vu := e.Interface()
		value = reflect.ValueOf(value).Convert(e.Type()).Interface()
		throwFail(t, AssertIs(vu == value, true), value, vu)
	}
}
开发者ID:4eek,项目名称:beego,代码行数:32,代码来源:orm_test.go

示例5: FindAll

func (orm *Model) FindAll(rowsSlicePtr interface{}) error {
	orm.ScanPK(rowsSlicePtr)
	sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
	if sliceValue.Kind() != reflect.Slice {
		return errors.New("needs a pointer to a slice")
	}

	sliceElementType := sliceValue.Type().Elem()
	st := reflect.New(sliceElementType)
	var keys []string
	results, _ := scanStructIntoMap(st.Interface())
	if orm.TableName == "" {
		orm.TableName = getTableName(rowsSlicePtr)
	}
	for key, _ := range results {
		keys = append(keys, key)
	}
	orm.ColumnStr = strings.Join(keys, ", ")

	resultsSlice, err := orm.FindMap()
	if err != nil {
		return err
	}

	for _, results := range resultsSlice {
		newValue := reflect.New(sliceElementType)
		scanMapIntoStruct(newValue.Interface(), results)
		sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(newValue.Interface()))))
	}
	return nil
}
开发者ID:dcosson,项目名称:beedb,代码行数:31,代码来源:beedb.go

示例6: updateAndGetSqlColumnsValues

func updateAndGetSqlColumnsValues(thing interface{}, table *tableMap, data map[string]interface{}) ([]string, []interface{}) {
	thingValue := reflect.Indirect(reflect.ValueOf(thing))
	columns := make([]string, 0, len(table.Columns))
	values := make([]interface{}, 0, len(table.Columns))

	for i := 0; i < len(table.Columns); i++ {
		column := table.Columns[i]

		if val, ok := data[column.Name]; ok {
			destField := thingValue.Field(column.Field)
			value := reflect.ValueOf(val)

			// assign the value from the data map to the destination struct field
			destField.Set(value)

			if column.Serialize {
				// TODO(jr): don't eat this marshal error value
				marshaled, _ := json.Marshal(val)
				values = append(values, string(marshaled))
			} else {
				values = append(values, reflect.Indirect(value).Interface())
			}
			columns = append(columns, column.Name)
		}
	}

	return columns, values
}
开发者ID:kelsieflynn,项目名称:m,代码行数:28,代码来源:mapper.go

示例7: Diff

func (tbl *TableCached) Diff(entA EntryCached, entB EntryCached) uint64 {
	ret := uint64(0)
	refvalA := reflect.Indirect(reflect.ValueOf(entA))
	refvalB := reflect.Indirect(reflect.ValueOf(entB))
	for _, v := range tbl.Table.Fields {
		if v.Primary {
			continue
		}
		if len(v.Name) <= 0 {
			continue
		}
		if v.VarIndex == -1 {
			continue
		}
		if v.VarIndex >= 64 {
			log.Println("Field index too damn high:", tbl.Table.Name, v.Name)
			return ^uint64(0)
		}
		bEq := refvalA.Field(v.VarIndex).Interface() == refvalB.Field(v.VarIndex).Interface()
		if !bEq {
			ret |= (uint64(1) << uint(v.VarIndex))
		}
	}
	return ret
}
开发者ID:ChristophPech,项目名称:servertest,代码行数:25,代码来源:dbcache.go

示例8: MarkChildEntryRem

func (tbl *TableCached) MarkChildEntryRem(ent EntryCached, ctIdx int, cent EntryCached) {
	ct := tbl.Children[ctIdx]
	cid := reflect.Indirect(reflect.ValueOf(cent)).Field(ct.Table._idxid).Interface()
	dbce := tbl.GetChildCacheEnt(ent, ctIdx)

	if dbce.ValsAdd != nil {
		for i, v := range dbce.ValsAdd {
			if reflect.Indirect(reflect.ValueOf(v)).Field(ct.Table._idxid).Interface() == cid {
				dbce.ValsAdd[i], dbce.ValsAdd = dbce.ValsAdd[len(dbce.ValsAdd)-1], dbce.ValsAdd[:len(dbce.ValsAdd)-1]
				break
			}
		}
	}
	if dbce.ValsMod != nil {
		for i, v := range dbce.ValsMod {
			if reflect.Indirect(reflect.ValueOf(v)).Field(ct.Table._idxid).Interface() == cid {
				dbce.ValsMod[i], dbce.ValsMod = dbce.ValsMod[len(dbce.ValsMod)-1], dbce.ValsMod[:len(dbce.ValsMod)-1]
				break
			}
		}
	}
	if dbce.ValsRem != nil {
		for _, v := range dbce.ValsRem {
			if reflect.Indirect(reflect.ValueOf(v)).Field(ct.Table._idxid).Interface() == cid {
				return
			}
		}
	}

	if dbce.ValsRem == nil {
		dbce.ValsRem = make([]interface{}, 0, 8)
	}

	dbce.ValsRem = append(dbce.ValsRem, cent)
}
开发者ID:ChristophPech,项目名称:servertest,代码行数:35,代码来源:dbcache.go

示例9: createJoinTable

func (scope *Scope) createJoinTable(field *StructField) {
	if relationship := field.Relationship; relationship != nil && relationship.JoinTableHandler != nil {
		joinTableHandler := relationship.JoinTableHandler
		joinTable := joinTableHandler.Table(scope.db)
		if !scope.Dialect().HasTable(scope, joinTable) {
			toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}

			var sqlTypes []string
			for idx, fieldName := range relationship.ForeignFieldNames {
				if field, ok := scope.Fields()[fieldName]; ok {
					value := reflect.Indirect(reflect.New(field.Struct.Type))
					primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false)
					sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+primaryKeySqlType)
				}
			}

			for idx, fieldName := range relationship.AssociationForeignFieldNames {
				if field, ok := toScope.Fields()[fieldName]; ok {
					value := reflect.Indirect(reflect.New(field.Struct.Type))
					primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false)
					sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+primaryKeySqlType)
				}
			}
			scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v) %s", scope.Quote(joinTable), strings.Join(sqlTypes, ","), scope.getTableOptions())).Error)
		}
		scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler)
	}
}
开发者ID:captainsafia,项目名称:livebook,代码行数:28,代码来源:scope_private.go

示例10: ReadParam

func (tbl *TableCached) ReadParam(ent EntryCached, rwp *RWParams) bool {
	if tbl.Cache == nil {
		return tbl.ReadUncached(ent, rwp)
	}
	refval := reflect.Indirect(reflect.ValueOf(ent))
	id := refval.Field(tbl._idxid).Interface()
	v, _ := tbl.Cache.Get(id)
	if v == nil {
		log.Println("ReadCached cache miss:", id)
		if !tbl.ReadUncached(ent, rwp) {
			return false
		}
		entCached := tbl.Table.NewValue().(EntryCached)
		entCached.CopyFrom(ent)
		refval := reflect.Indirect(reflect.ValueOf(entCached))
		if tbl._idxdbcache != -1 {
			refval.Field(tbl._idxdbcache).Set(dbCacheTypeZero)
		}

		if tbl.Children != nil {
			tbl.ClearChildren(entCached)
		}
		tbl.Cache.Set(id, entCached)
	} else {
		entCached, _ := v.(EntryCached)
		tbl.ReadAccess(entCached, rwp)
		ent.CopyFrom(entCached)
		if tbl.Children != nil {
			tbl.ReadChildrenParams(ent, rwp)
		}
	}
	return true
}
开发者ID:ChristophPech,项目名称:servertest,代码行数:33,代码来源:dbcache.go

示例11: GetStructs

// query by s and return a slice by type s
// field mapping rule is: HelloWorld => hello_world
// mean that struct's field "HelloWorld" in database table's field is "hello_world"
// table name mapping use the same rule as field
// @param slicePtr: a pointer to a slice
//     var blogs []Blog
//     err := db.GetStructs(&blogs, SqlQueryInfo{})
func (db *DB) GetStructs(slicePtr interface{}, qi SqlQueryInfo) error {
	ptr := reflect.ValueOf(slicePtr)
	if ptr.Kind() != reflect.Ptr {
		return errors.New("db.GetStructs: needs a pointer to a slice")
	}
	sliceValue := reflect.Indirect(ptr)
	if sliceValue.Kind() != reflect.Slice {
		return errors.New("db.GetStructs: needs a pointer to a slice")
	}

	structType := sliceValue.Type().Elem()

	rows, fields, err := db.rawSelectByStruct(structType, qi)
	if err != nil {
		return err
	}
	defer rows.Close()

	for rows.Next() {
		v := reflect.New(structType)
		err = rawScanStruct(v, fields, rows)
		if err != nil {
			return err
		}
		fmt.Println(v.Interface())
		sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(v.Interface()))))
	}

	return nil
}
开发者ID:Kehao,项目名称:playGo,代码行数:37,代码来源:funDb.go

示例12: machoUpdateSections

func machoUpdateSections(r loadCmdReader, seg, sect reflect.Value, delta uint64) error {
	iseg := reflect.Indirect(seg)
	nsect := iseg.FieldByName("Nsect").Uint()
	if nsect == 0 {
		return nil
	}
	sectOffset := int64(iseg.Type().Size())

	isect := reflect.Indirect(sect)
	offsetField := isect.FieldByName("Offset")
	reloffField := isect.FieldByName("Reloff")
	sectSize := int64(isect.Type().Size())
	for i := uint64(0); i < nsect; i++ {
		if err := r.ReadAt(sectOffset, sect.Interface()); err != nil {
			return err
		}
		if offsetField.Uint() != 0 {
			offsetField.SetUint(offsetField.Uint() + delta)
		}
		if reloffField.Uint() != 0 {
			reloffField.SetUint(reloffField.Uint() + delta)
		}
		if err := r.WriteAt(sectOffset, sect.Interface()); err != nil {
			return err
		}
		sectOffset += sectSize
	}
	return nil
}
开发者ID:Greentor,项目名称:go,代码行数:29,代码来源:macho_combine_dwarf.go

示例13: SetFormValues

// set values from one struct to other struct
// both need ptr struct
func SetFormValues(from interface{}, to interface{}, skips ...string) {
	val := reflect.ValueOf(from)
	elm := reflect.Indirect(val)

	valTo := reflect.ValueOf(to)
	elmTo := reflect.Indirect(valTo)

	panicAssertStructPtr(val)
	panicAssertStructPtr(valTo)

outFor:
	for i := 0; i < elmTo.NumField(); i++ {
		toF := elmTo.Field(i)
		name := elmTo.Type().Field(i).Name

		// skip specify field
		for _, skip := range skips {
			if skip == name {
				continue outFor
			}
		}
		f := elm.FieldByName(name)
		if f.Kind() != reflect.Invalid {
			// set value if type matched
			if f.Type().String() == toF.Type().String() {
				toF.Set(f)
			}
		}
	}
}
开发者ID:thuongdinh,项目名称:beegowebapp,代码行数:32,代码来源:forms.go

示例14: handleBelongsToPreload

func (scope *Scope) handleBelongsToPreload(field *Field, conditions []interface{}) {
	relation := field.Relationship
	primaryKeys := scope.getColumnAsArray(relation.ForeignFieldName)
	if len(primaryKeys) == 0 {
		return
	}

	results := makeSlice(field.Struct.Type)
	associationPrimaryKey := scope.New(results).PrimaryField().Name

	scope.Err(scope.NewDB().Where(primaryKeys).Find(results, conditions...).Error)
	resultValues := reflect.Indirect(reflect.ValueOf(results))

	for i := 0; i < resultValues.Len(); i++ {
		result := resultValues.Index(i)
		if scope.IndirectValue().Kind() == reflect.Slice {
			value := getRealValue(result, associationPrimaryKey)
			objects := scope.IndirectValue()
			for j := 0; j < objects.Len(); j++ {
				object := reflect.Indirect(objects.Index(j))
				if equalAsString(getRealValue(object, relation.ForeignFieldName), value) {
					object.FieldByName(field.Name).Set(result)
				}
			}
		} else {
			scope.SetColumn(field, result)
		}
	}
}
开发者ID:useidel,项目名称:notary,代码行数:29,代码来源:preload.go

示例15: Convert

func (j *JavaToGoObjectArray) Convert(obj *gojvm.Object) (err error) {
	objs := GetEnv().ToObjectArray(obj)

	r_value := reflect.ValueOf(j.list)

	if r_value.Type().Kind() != reflect.Ptr {
		return errors.New("JavaToGoList.Convert: dest not ptr")
	}

	r_slice := reflect.Indirect(r_value)
	if r_slice.Type().Kind() != reflect.Slice {
		return errors.New("JavaToGoList.Convert: dest ptr , does not point to slice")
	}

	for i := 0; i < len(objs); i++ {
		r_newElemV := reflect.New(r_slice.Type().Elem().Elem())
		c := &Callable{}
		j.item.Dest(c)
		if err = j.item.Convert(objs[i]); err != nil {
			return err
		}
		if err = j.item.CleanUp(); err != nil {
			return err
		}

		reflect.Indirect(r_newElemV).FieldByName("Callable").Set(reflect.ValueOf(c))
		r_newSlice := reflect.Append(r_slice, r_newElemV)
		r_slice.Set(r_newSlice)
	}

	return
}
开发者ID:skanjo,项目名称:javabind,代码行数:32,代码来源:runtime.go


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