英文:
Is there a built-in means to remove the first item from an array?
问题
学习Go语言,真是一门很棒的语言。
在Go语言中,有没有内置的方法可以删除数组中的第一个元素?有点像PHP中的array_shift函数。
我有一个字符串,"the brown fox jumps"。
我找到了strings.Fields()
函数,它可以将字符串转换为数组。我想将该字符串转换为两个字符串:
"the"和"brown fox jumps"
words := strings.Fields(theFoxString)
firstWord := words[0]
otherWords := strings.Join(words[1:], " ")
谢谢你的帮助!
英文:
Learning Go, what a great language.
Is there a built-in means to remove the first item in an array? Kind of like PHP's array_shift
I have a string, "the brown fox jumps"
I've found strings.Fields()
which turns it into an array. I'd like to turn that string into two strings:
"the", "brown fox jumps"
words := strings.Fields(theFoxString)
firstWord := // unshift first word from words
otherWords := // join what's left of words with ' '
Thank you for your help!
答案1
得分: 5
如果我们有一个切片 a
,我们可以这样做:
x, a := a[0], a[1:]
所以使用你的代码,我们可以得到:
words := strings.Fields(theFoxString)
firstWord, otherWords := words[0], words[1:]
请记住,底层数组并没有改变,但我们用来查看该数组的切片已经改变了。对于大多数情况来说,这是可以的(甚至在性能上有优势!),但这是需要注意的一点。
来源:
https://github.com/golang/go/wiki/SliceTricks
英文:
If we have any slice a
, we can do this:
x, a := a[0], a[1:]
So using your code, we get:
words := strings.Fields(theFoxString)
firstWord, otherWords := words[0], words[1:]
Keep in mind the underlying array hasn't changed, but the slice we are using to look at that array has. For most purposes this is ok (and even advantageous performance wise!), but it is something to be aware of.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论