Unpack slices on assignment?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)