How to generate numbers sequentially in go language

藏色散人
Release: 2020-12-17 16:39:13
Original
3158 people have browsed it

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
}
Copy after login

Use this:

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

Output (try it on Go Playground):

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

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]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!