Created
September 21, 2016 05:17
-
-
Save natdm/862617507e81d4a5616f1d12e728b7cc to your computer and use it in GitHub Desktop.
Messing with golang arrays and slices, for kicks.
This file contains hidden or 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() { | |
//initialize an array with len/cap 6 | |
a := [6]string{"G", "o", "l", "a", "n", "g"} | |
// print the address of the first letter in a | |
printAddr(&a[0]) | |
//Copy arr a to slice b | |
b := a[:] | |
//print the address of b[0], which is the same address as a[0] | |
printAddr(&b[0]) | |
//print the len and cap of arr a and slice b, they're the same | |
fmt.Printf("len(a)[%v], cap(a)[%v], len(b)[%v], cap(b)[%v]\n", | |
len(a), cap(a), len(b), cap(b)) | |
//append more than the cap of slice b | |
b = append(b, []string{"a","b","c", "b"}...) | |
//notice the len/cap change | |
fmt.Printf("len(a)[%v], cap(a)[%v], len(b)[%v], cap(b)[%v]\n", | |
len(a), cap(a), len(b), cap(b)) | |
//the address of b[0] is different than it was | |
printAddr(&b[0]) | |
} | |
func printAddr(a *string) { | |
fmt.Println(a) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment