Skip to content

Instantly share code, notes, and snippets.

@josephspurrier
Created December 22, 2014 16:12
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 josephspurrier/b5713f9a534afe3cfdd2 to your computer and use it in GitHub Desktop.
Save josephspurrier/b5713f9a534afe3cfdd2 to your computer and use it in GitHub Desktop.
Golang - Differences between Array and Slice
package main
import (
"fmt"
"reflect"
"strings"
)
func main() {
// Arrays, slices (and strings)
// http://blog.golang.org/slices
// Playground: http://play.golang.org/p/94mqg0BxiQ
// Nil slice has length and capacity of 0
var a []int
// Error: throws an index out of range
// a[0] = 1;
// Must append to nil slice
a = append(a, 4)
// Outputs: [4] []int
fmt.Println(a, reflect.TypeOf(a))
// Fixed-size slice has length of 2 and capacity of 2
b := []int{1, 2}
b = append(b, 3)
// Outputs: [1 2 3] []int
fmt.Println(b, reflect.TypeOf(b))
// Empty slice has length of 2 and capacity of 0
c := make([]int, 2)
c[0] = 5
c = append(c, 6)
// Outputs: [5 0 6] []int
fmt.Println(c, reflect.TypeOf(c))
// Empty array has length of 2 and capacity of 0
var d [2]int
d[0] = 7
d[1] = 8
// Outputs: [7 8] [2]int
fmt.Println(d, reflect.TypeOf(d))
// String array
var s1 [2]string
s1[0] = "Yes"
s1[1] = "No"
// This will ERROR
//fmt.Println(strings.Join(s1, ","))
// String slice
s2 := make([]string, 2)
s2[0] = "Yes"
s2[1] = "No"
// This will work
fmt.Println(strings.Join(s2, ","))
}
@gurbachan-singh-jabong
Copy link

How here i will find difference between array and slice :

// Nil slice has length and capacity of 0
var a []int

// Empty array has length of 2 and capacity of 0
var d [2]int

I have alot confusion between them

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment