如何仅用于显示目的递增索引?

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

How do I increment the index for display purposes only?

问题

这段代码从索引0开始打印数据,但我希望它看起来索引从1开始。

给定结果

0 Foo
1 Bar

所需结果

1 Foo
2 Bar

代码

package main

import "fmt"

func main() {
    a := []string{"Foo", "Bar"}
    for i, s := range a {
        fmt.Println(i+1, s)
    }
}
英文:

This code starts printing the data from the 0 index but I want it to seem as if the index starts at 1.

Given Result

0 Foo
1 Bar

Required Result

1 Foo
2 Bar

Code

package main

import "fmt"

func main() {
	a := []string{"Foo", "Bar"}
	for i, s := range a {
		fmt.Println(i, s)
	}
}

答案1

得分: 3

你要翻译的内容如下:

实现你所寻找的最简单方法是通过以下递增方式:

package main

import "fmt"

func main() {
    a := []string{"Foo", "Bar"}
    for i, s := range a {
        fmt.Println(i+1, s)
    }
}

输出结果:

1 Foo
2 Bar
英文:

The simplest way to achieve what you are looking for is by an increment as follows:

package main

import "fmt"

func main() {
	a := []string{"Foo", "Bar"}
	for i, s := range a {
		fmt.Println(i+1, s)
	}
}

Output:

1 Foo
2 Bar

huangapple
  • 本文由 发表于 2022年9月6日 23:18:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/73624377.html
匿名

发表评论

匿名网友

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

确定