Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Create a slice in Go

Slices can be created in Go in two syntax.

Declaration with elements, array syntax can be used to create a slice without array length argument
carSlice := []string{"Audi", "BMW"}


Here car slice is created with initial capacity of 2 and can be modified upon adding more elements via append.

Declaration with empty elements using make method
personNameSlice := make([]string, 0)



Complete example for creating slices and adding elements in Go
package main

import "fmt"

func main() {
    carSlice := []string{"Audi", "BMW"}

    carSlice = append(carSlice, "Benz")

    fmt.Printf("%v \n", carSlice)

    personNameSlice := make([]string, 0)

    personNameSlice = append(personNameSlice, "hello")

    fmt.Printf("%v", personNameSlice)

}


Output
[Audi BMW Benz]
[hello]