Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Appending elements to slices in Golang
package main
import "fmt"
func main() {
var names []string /* Zero value of a slice is nil */
fmt.Println(names, len(names), cap(names)) /* Returns [] 0 0 */
names = append(names, "John", "Bill", "Steve")
fmt.Println(names, len(names), cap(names)) /* Returns [John Bill Steve] 3 3 */
vegies := [...]string{"Potato", "Tomato", "Eggplant", "Onion", "Capsicum"}
vegslice := vegies[1:3]
/* Returns [Tomato Eggplant] 2 4 */
fmt.Println(vegslice, len(vegslice), cap(vegslice))
vegslice = append(vegslice, "Okra", "Cabbage")
/* Returns [Tomato Eggplant Okra Cabbage] 4 4 */
fmt.Println(vegslice, len(vegslice), cap(vegslice))
vegslice = append(vegslice, "Lettuce", "Bottlegaurd")
/* Returns [Tomato Eggplant Okra Cabbage Lettuce Bottlegaurd] 6 8 */
fmt.Println(vegslice, len(vegslice), cap(vegslice))
}
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.