Skip to content

Instantly share code, notes, and snippets.

@britonad
Last active June 25, 2020 16:14
Show Gist options
  • Save britonad/68d5313b3cae0feb98e0ac0c49483fd4 to your computer and use it in GitHub Desktop.
Save britonad/68d5313b3cae0feb98e0ac0c49483fd4 to your computer and use it in GitHub Desktop.
How `cap` built-in differs from `len` one in Golang.
package main
import "fmt"
func main() {
/*
array address is 0xc000016420.
array values are [5]int{1, 2, 3, 4, 5}.
array type is [5]int.
array length is 5.
array capacity is 5.
s address is 0xc00000c060.
s values are []int{1, 2}.
s type is []int.
s length is 2.
s capacity is 5.
*/
array := [5]int{1, 2, 3, 4, 5}
s := array[0:2]
fmt.Printf("array address is %p.\n", &array)
fmt.Printf("array values are %#v.\n", array)
fmt.Printf("array type is %T.\n", array)
fmt.Printf("array length is %d.\n", len(array))
fmt.Printf("array capacity is %d.\n", cap(array))
fmt.Println()
fmt.Printf("s address is %p.\n", &s)
fmt.Printf("s values are %#v.\n", s)
fmt.Printf("s type is %T.\n", s)
fmt.Printf("s length is %d.\n", len(s))
fmt.Printf("s capacity is %d.\n", cap(s))
}
@britonad
Copy link
Author

package main

import "fmt"

func main() {
	/*
		[]
		[0 0 0 0 0]
		[0 0]
		Length is 2
		Capacity is 3
	*/
	a := make([]int, 0, 5)
	fmt.Println(a)

	a = a[:cap(a)]
	fmt.Println(a)

	a = a[2:4]
	fmt.Println(a)
	fmt.Printf("Length is %d\n", len(a))
	fmt.Printf("Capacity is %d\n", cap(a))
}

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