duangengruan2144 2018-02-02 14:54
浏览 14
已采纳

在Go中初始化成员时是否只能使用返回值之一?

I understand how to use multiple return values in go. I further understand that in most cases one of the returns is an error, so ignoring returned values can be dangerous.

Is there a way to ignore a value in struct initializer like this? The below example does not work as Split returns two values, but I am interested only in the first one. I can of course create a variable but...

someFile := "test/filename.ext"

contrivedStruct := []struct{
    parentDir string
}{
    { parentDir: filepath.Split(someFile) },
}
  • 写回答

2条回答 默认 最新

  • dsxgby126001 2018-02-02 15:20
    关注

    It's not possible to use only one of the return values when initializing members in Go.

    Using variables clearly expresses your intent.

    Go sometimes feels like it could be more succinct, but the Go authors favoured readability over brevity.

    Alternatively, use a wrapper function. There are several 'Must' wrapper functions in the standard library, like: template.Must.

    func first(args ...string) string {
        return args[0]
    }
    

    For your particular example, splitting paths, see filepath.Base or filepath.Dir.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部