英文:
How to print out non-contiguous sections of the slice in Go?
问题
想知道在Go语言中是否有一种方法可以打印出切片中不连续的部分。
示例:
words := []string{"Mary","had","a","little","lamb"}
我想要打印出切片中的"Mary"和"lamb"。
类似于:
fmt.Printf("%s\n", words[0],[5])
...显然这样是行不通的...有没有其他方法?:(
非常感谢!
英文:
Wondering if there is a way to print out non contiguous portions of slice in Gol?
Example:
> words := []string{"Mary","had","a","little","lamb"}
and I want to print out "Mary" and "lamb" from the slice?
Something along the lines of:
> fmt.Printf("%s\n", words[0],[5])
...which obviously this won't work... Is there a way ?
Thanks a lot!!
答案1
得分: 2
你可以对切片进行索引,只是你的操作方式不正确。
fmt.Printf("%s %s\n", words[0], words[5])
你的索引语法不起作用,因为第二个变量只是索引部分,没有包含words
。此外,你的格式化字符串是错误的,只有一个%s
,这意味着Printf只期望在此之后有一个参数。每个参数都需要一个格式化符号。
英文:
You can index into the slice, you just are doing it wrong.
fmt.Printf("%s %s\n", words[0], words[5])
Your syntax for indexing didn't work because the second variable was just the index stuff without words
. Additionally your format string was wrong, a single %s
which means Printf is only expecting a single argument after that. Gotta have one formatter per arg.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论