doutuo3899 2013-11-07 09:27
浏览 65
已采纳

在分配作业时解压切片?

Is there an elegant way in Go to do multiple assignments from arrays like in Python? Here is a Python example of what I'm trying to do (split a string and then assign the resulting array into two variables).

python:
>>> a, b = "foo;bar".split(";")

My current solution is:

x := strings.Split("foo;bar", ";")
a, b := x[0], x[1]

I'm can see this getting messy in some constructs. The practical example I'm currently facing is a bookmark file parsing and assigning to a map:

bookmark := make(map[string]string)
x := strings.Split("foo\thttps://bar", "\t")
name, link := x[0], x[1]
bookmark[name] = link

Now I have a useless variable x sitting around. I'd like to do something like:

bookmark := make(map[string]string)
name, line := strings.Split("foo\thttps://bar", "\t")
bookmark[name] = link

but that's invalid.

  • 写回答

3条回答 默认 最新

  • doudu9094 2013-11-07 09:48
    关注

    As Sergio Tulentsev mentioned, general packing/unpacking as is done in Python is not supported. I think the way to go there is to define your own small ad-hoc function using multiple return values:

    func splitLink(s, sep string) (string, string) {
        x := strings.Split(s, sep)
        return x[0], x[1]
    }
    

    And you can then write:

    name, link := splitLink("foo\thttps://bar", "\t")
    

    But this will obviously work only when at least two substrings are being split, and silently ignore if more than two were. If this is something you use a lot, it might make your code more readable though.

    --EDIT--

    Another way to unpack an array is via variadic pointer arguments:

    func unpack(s []string, vars... *string) {
        for i, str := range s {
            *vars[i] = str
        }
    }
    

    Which let you write:

    var name, link string
    unpack(strings.Split("foo\thttps://bar", "\t"), &name, &link)
    bookmarks[name] = link
    

    This will work for any array size, but it is arguably less readable, and you have to declare your variables explicitly.

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

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号