daily pastebin goal
81%
SHARE
TWEET

Untitled

a guest May 16th, 2018 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var s1 []int         // nil slice
  2. s2 := []int{}        // non-nil, empty slice
  3. s3 := make([]int, 0) // non-nil, empty slice
  4.  
  5. fmt.Println("s1", len(s1), cap(s1), s1 == nil, s1[:], s1[:] == nil)
  6. fmt.Println("s2", len(s2), cap(s2), s2 == nil, s2[:], s2[:] == nil)
  7. fmt.Println("s3", len(s3), cap(s3), s3 == nil, s3[:], s3[:] == nil)
  8.  
  9. for range s1 {}
  10. for range s2 {}
  11. for range s3 {}
  12.    
  13. s1 0 0 true [] true
  14. s2 0 0 false [] false
  15. s3 0 0 false [] false
  16.    
  17. s := make([]int, 0, 100)
  18. fmt.Println("Empty:", len(s) == 0, ", but capacity:", cap(s))
  19.    
  20. Empty: true , but capacity: 100
  21.    
  22. type SliceHeader struct {
  23.     Data uintptr
  24.     Len  int
  25.     Cap  int
  26. }
  27.    
  28. var s1 []int
  29. s2 := []int{}
  30. s3 := make([]int, 0)
  31.  
  32. fmt.Printf("s1 (addr: %p): %+8vn",
  33.     &s1, *(*reflect.SliceHeader)(unsafe.Pointer(&s1)))
  34. fmt.Printf("s2 (addr: %p): %+8vn",
  35.     &s2, *(*reflect.SliceHeader)(unsafe.Pointer(&s2)))
  36. fmt.Printf("s3 (addr: %p): %+8vn",
  37.     &s3, *(*reflect.SliceHeader)(unsafe.Pointer(&s3)))
  38.    
  39. s1 (addr: 0x1040a130): {Data:       0 Len:       0 Cap:       0}
  40. s2 (addr: 0x1040a140): {Data: 1535812 Len:       0 Cap:       0}
  41. s3 (addr: 0x1040a150): {Data: 1535812 Len:       0 Cap:       0}
  42.    
  43. var n []int
  44. n == nil // true
  45.    
  46. var n []int
  47. len(n) == cap(n) == 0 // true
  48. n = append(n, 123)
  49. len(n) == 1 // true
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top