duandie0884
2015-02-04 06:16 阅读 24
已采纳

进行类型推断和命名返回变量

In Go if you give a name to the return variables they are initialised to their zero values when the function begins. I'm using this feature below with the err variable on the line usr, err = user.Current(). Is it possible to use type inference for usr variable and not for the err variable? I don't really want to declare var usr *user.user I would much rather use type inference here.

func getConfigFilepath(userSuppliedFilepath string) (filepath string, err error) {

    if userSuppliedFilepath == "" {
        usr, err = user.Current()
        filepath = path.Join(usr.HomeDir, ".myprogram.config.json")
    }

    return
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    duanchigeng4313 duanchigeng4313 2015-02-04 06:31

    No, you can't do what you want to do.

    Your choices are to not use named returns, or like you said declare

    var usr *user.User 
    usr, err = user.Current()
    

    In some circumstances you could do that, but in your case you are are creating a new err because you are within the if block and it is making a locally scoped reference to a new err.

    点赞 评论 复制链接分享
  • duanbiaojin8860 duanbiaojin8860 2015-02-04 07:05

    You can if you slightly restructure your code and you don't put the user.Current() call in another block (if in your case), then you can do it with the := Short variable declaration:

    func getConfigFilepath(userSuppliedFilepath string) (filepath string, err error) {
        if userSuppliedFilepath != "" {
            return userSuppliedFilepath, nil
        }
    
        usr, err := user.Current()
        filepath = path.Join(usr.HomeDir, ".myprogram.config.json")
        return
    }
    

    Edit:

    You might say this code is longer than your original, but note that your original code is not yet valid and is also incomplete because it does not handle the case when userSuppliedFilepath is provided. You should compare the proposed code to the full and valid version of your code which is below:

    func getConfigFilepath(userSuppliedFilepath string) (filepath string, err error) {
        if userSuppliedFilepath == "" {
            var usr *user.User
            usr, err = user.Current()
            filepath = path.Join(usr.HomeDir, ".myprogram.config.json")
        } else {
            filepath = userSuppliedFilepath
        }
    
        return
    }
    

    And now the proposed code isn't longer (on the contrary, it's a little shorter).

    点赞 评论 复制链接分享

相关推荐