Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Declare Arrays in Golang
package main
import (
"fmt"
"reflect"
)
func main() {
/* Declaring an array and adding elements */
var names [3]string //string array with length 3
names[0] = "Alice" // array index starts at 0
names[1] = "Bob"
names[2] = "Celine"
/* Shorthand declaration */
mynames := [3]string{"Alice", "Bob", "Celine"}
fmt.Println(names, mynames)
/* Compiler determines the length of array */
scores := [...]int{12, 78, 50}
fmt.Println(scores, len(scores))
/* The size of the array is a part of the type - [3]string */
fmt.Println(mynames, reflect.TypeOf(mynames)) /* Prints: [Alice Bob Celine] [3]string*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.