Last active
January 27, 2019 06:19
-
-
Save cjgiridhar/5c25f6bd11e8f57d26f6230b9e73df94 to your computer and use it in GitHub Desktop.
Appending elements to slices in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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