V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
johnlin
V2EX  ›  问与答

关于 GO 函数值传递的问题

  •  
  •   johnlin · 2022-02-10 11:38:34 +08:00 · 793 次点击
    这是一个创建于 804 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题描述:
    调用 OnceDo 方法,传入一个 userModel 的结构体地址,然后在 OnceDo 中通过 interface 类型的参数接收并且通过匿名方法获得 user 信息的值,我想在 HandleUserInfo 方法中拿到 user 信息,这个怎么处理
    方案:
    目前想到的也就是通过反射一个个遍历改变 userModel 的每个值,为了简便直接用了 json.Unmarshal 方法
    需要解决的问题:
    各位大佬还有没有其它方案或者比 json.Unmarshal 更效率的方法?

    //处理用户信息
    func HandleUserInfo(userId int) (bool,*model.User) {
    	cacheKey := fmt.Sprintf(util.BackendCacheKeyList[0]+"%d",userId)
    	userModel := &model.User{}
    	fetchDataFromDb := func() (interface{}, error) {
    		err,userEntity := service.ServiceGroupApp.SystemServiceGroup.GetUserInfo(userId)
    		return	userEntity,err
    	}//该匿名函数返回 mysql user 表的数据值
    	if err := redisClient.OnceDo(global.GVA_REDIS,cacheKey, userModel, util.CacheTimeList[0], fetchDataFromDb);err == nil {
    		return true, userModel
    	}
    	return false, userModel
    }
    //调用函数--查询缓存,存在返回缓存数据,不存在查询数据库
    func OnceDo(client *redis.Client, key string, obj interface{}, expiration time.Duration, do func() (data interface{}, err error)) (err error) {
    	//第二次调用可以直接忽略
        if RExists(client, key) == true {
    		value, err := client.Get(context.Background(), key).Bytes()
    		if err == nil {
    			return json.Unmarshal(value, obj)
    		}
    	}
        //第一次调用
    	obj, err = do()
    	if err == nil {
    		p, mErr := json.Marshal(obj)
    		if mErr == nil {
    			//主要问题就是这个 obj 参数,我想在 HandleUserInfo 拿到这个 obj 的值,目前我想到的最简单的就是通过 json.Unmarshal 方法解决
    			json.Unmarshal(p, obj)
    			//
    			return client.Set(context.Background(), key, p, expiration).Err()
    		}
    		return mErr
    	}
    	return err
    }
    
    johnlin
        1
    johnlin  
    OP
       2022-02-10 13:48:13 +08:00
    OnceDo 方法写错了<br />
    func OnceDo(client *redis.Client, key string, obj interface{}, expiration time.Duration, do func() (data interface{}, err error)) (err error) {
    if RExists(client, key) == true {
    value, err := client.Get(context.Background(), key).Bytes()
    if err == nil {
    return json.Unmarshal(value, obj)
    }
    }

    newData, oErr := do()
    if oErr == nil {
    p, mErr := json.Marshal(newData)
    if mErr == nil {
    json.Unmarshal(p, obj)
    return client.Set(context.Background(), key, p, expiration).Err()
    }
    return mErr
    }
    return err
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4850 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 01:09 · PVG 09:09 · LAX 18:09 · JFK 21:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.