Skip to content

Instantly share code, notes, and snippets.

@cjgiridhar
Last active January 27, 2019 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjgiridhar/5c25f6bd11e8f57d26f6230b9e73df94 to your computer and use it in GitHub Desktop.
Save cjgiridhar/5c25f6bd11e8f57d26f6230b9e73df94 to your computer and use it in GitHub Desktop.
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