DEV Community

Cover image for golang print array
tcs224
tcs224

Posted on

golang print array

When programming you often work with data. This data can be a single digit, a single word, but often it's much more than that. Programmers often work with a collection of data. A collection could be an array.

The Go programming language (golang). The Go programming language lets you define and work with arrays. An array can be a list of integers, a list of strings and so on.

You can define an array in golang like this, one array of integers and one array of strings:

setA := []int{1, 2, 3,4,5}
setB := [5]string{"one", "two", "three", "four", "five"}

Then you could just output the whole array, like this:

package main

import (
    "fmt"
)

func main() {

        setA := []int{1, 2, 3,4,5}
        setB := [5]string{"one", "two", "three", "four", "five"}

    fmt.Println(setA)
    fmt.Println(setB)
}

But this only shows the raw array. How can you iterate over it?

Example

Do you want to loop over an array and format it at the same time or do something else with the data? You can use a for loop to achieve that.

for _, value := range setA {
  fmt.Printf("- %d\n", value)
}

That gives you this code:

package main

import (
    "fmt"
)

func main() {

        setA := []int{1, 2, 3,4,5}
        setB := [5]string{"one", "two", "three", "four", "five"}

        for _, value := range setA {
          fmt.Printf("- %d\n", value)
        }

        for _, str := range setB {
          fmt.Printf("* %s\n", str)
        }
}

which outputs the following:

- 1
- 2
- 3
- 4
- 5
* one
* two
* three
* four
* five

The difference in style, because there are two loops which call fmt.Printf differently and to demonstrate there are two arrays.

So for both iterating over a string and integer array is the same, except the formatting in the Printf function.

Top comments (0)