Home >Backend Development >Golang >How to generate numbers sequentially in go language

How to generate numbers sequentially in go language

藏色散人
藏色散人Original
2020-12-16 14:56:023257browse

Go language implements the method of sequentially generating numbers: first create a go code sample file; then customize a makeRange method; and finally use the "for i := range a {a[i] = min i}" method Just generate numbers sequentially.

How to generate numbers sequentially in go language

Environment of this article: Windows 10 system, Go1.11.2 version, this article is applicable to all brands of computers.

Recommended: "golang tutorial"

There is no range equivalent to PHP in the Go standard library (this PHP function can return a range containing an array of elements between low and high).

We have to create one ourselves.

The easiest is to use a for loop:

func makeRange(min, max int) []int {
    a := make([]int, max-min+1)
    for i := range a {
        a[i] = min + i
    }
    return a
}

Use this:

a := makeRange(10, 20)
fmt.Println(a)

Output (try it on Go Playground):

[10 11 12 13 14 15 16 17 18 19 20]

Also note , if the range is small, you can use compound literals:

a := []int{1, 2, 3}
fmt.Println(a) // Output is [1 2 3]

The above is the detailed content of How to generate numbers sequentially in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn