Quick actions

cmd+k|ctrl+k

Navigation

Languages

Arrays / Create array / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-09-07T17:55:17Z

Updated

2019-09-07T17:55:17Z

package main

import "fmt"

func main() {
	// Creating arrays of 6 elements of type int
	var array1 = [6]int{1, 2, 3, 4, 5, 6}
	// the compiler will derive the size of the array
	var array2 = [...]int{1, 2, 3, 4, 5, 6} 

	fmt.Println("array1:", array1)
	fmt.Println("array2:", array2)

	// Creating arrays with default values inside:
	zeros := [8]int{}       // Create a list of 8 int filled with 0
	ptrs := [8]*int{}       // a list of int pointers, filled with 8 nil references ( <nil> )
	emptystr := [8]string{} // a list of string filled with 8 times ""

	fmt.Println("zeroes:", zeros)      // > [0 0 0 0 0 0 0 0]
	fmt.Println("ptrs:", ptrs)         // > [<nil> <nil> <nil> <nil> <nil> <nil> <nil> <nil>]
	fmt.Println("emptystr:", emptystr) // > [       ]
	// values are empty strings, separated by spaces,
	// so we can just see separating spaces

	// Arrays are also working with a personalized type
	type Data struct {
		Number int
		Text   string
	}

	// Creating an array with 8 'Data' elements
	// All the 8 elements will be like {0, ""} (Number = 0, Text = "")
	structs := [8]Data{}

	fmt.Println("structs:", structs) // > [{0 } {0 } {0 } {0 } {0 } {0 } {0 } {0 }]
	// prints {0 } because Number are 0 and Text are empty; separated by a space
}
INFO