如何在Go中打印出切片的非连续部分?

huangapple go评论77阅读模式
英文:

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 ? 如何在Go中打印出切片的非连续部分?

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.

huangapple
  • 本文由 发表于 2015年7月16日 00:08:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/31435617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定