在分配作业时解压切片? [英] Unpack slices on assignment?
问题描述
在Go中,有没有一种优雅的方法可以像在Python中那样从数组中进行多个赋值?这是我要尝试执行的Python示例(拆分一个字符串,然后将结果数组分配给两个变量).
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(";")
我当前的解决方案是:
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
现在我周围有一个无用的变量x
.我想做类似的事情:
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
但这是无效的.
推荐答案
正如Sergio Tulentsev所述,不支持Python中的常规打包/解包.我认为方法是使用多个返回值定义自己的小型即席函数:
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]
}
然后您可以写:
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.
-编辑-
解数组的另一种方法是通过可变指针参数:
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
}
}
您可以这样写:
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.
这篇关于在分配作业时解压切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!