Go Array Definition

Introduction

Go array is a numbered sequence of elements of a single type with a fixed length.

In Go, array look like this:

var x [5]int 

x is an example of an array that is composed of five int values.

Try running the following program:

package main/*from  ww  w  .  j  a v  a2s  .  co m*/

import "fmt" 

func main() { 
    var x [5]int 
    x[4] = 100 
    fmt.Println(x) 
} 

x[4] = 100 means "set the fifth element of the array x to 100."

Go arrays are indexed starting from 0.

Here's an example program that uses arrays:

package main//from w  w w  .  j  a v a  2s.  c  o m

import "fmt" 

func main() { 
    var x [5]float64 
    x[0] = 9 
    x[1] = 3 
    x[2] = 7 
    x[3] = 8 
    x[4] = 2 

    var total float64 = 0 
    for i  := 0; i < 5; i++ { 
        total += x[i] 
    } 
    fmt.Println(total / 5) 
} 

Go also provides a shorter syntax for creating arrays:

x  := [5]float64{ 98, 93, 77, 82, 83 } 

Go allows you to break long line:

x  := [5]float64{ 
    98, 
    93, 
    77, 
    82, 
    83, 
} 

Notice the extra trailing , after 83.

This is required by Go and it allows us to easily remove an element from the array by commenting out the line:

x  := [4]float64{ 
    98, 
    93, 
    77, 
    82, 
    // 83, 
} 



PreviousNext

Related