Last active
August 29, 2015 14:00
-
-
Save mmcdaris/d66cf026585ac7837873 to your computer and use it in GitHub Desktop.
used gobyexample and the go article on slices: http://blog.golang.org/go-slices-usage-and-internals
This file contains 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() { | |
slicesOne() | |
makeSlice() | |
slicesTwo() | |
sliceInternals() | |
} | |
func slicesOne() { | |
// slices are like arrays but they don't have a specified length | |
slc := []string{"morgan", "learns", "go"} | |
fmt.Println(slc) | |
} | |
func makeSlice() { | |
// slices can be made with the make function: func make([]T, length, capacity) []T | |
// T would be the element type like 'string' above | |
// make example coming up! | |
var slc []byte | |
slc = make([]byte, 5, 5) // []T: []byte, len: 5, cap: f | |
// s == []byte{0, 0, 0, 0, 0} | |
fmt.Println(slc) | |
// capacity is optional and if not provided explicitly it will == length | |
proveIt := make([]byte, 10) | |
fmt.Println(proveIt) | |
// don't beleive me?? lets check it out! | |
lenSameAsCap := cap(proveIt) == len(proveIt) | |
fmt.Println("cap:", cap(proveIt), "len:", len(proveIt), "equal?:", lenSameAsCap) | |
} | |
func slicesTwo() { | |
// zero value of a slice is nil len and cap will return 0 for a nil slice | |
b := []string{"g", "o", "l", "a", "n", "g"} | |
// sick ass prints | |
fmt.Println("b[1:4] :", b[1:4]) | |
fmt.Println("b[1:] :", b[1:]) | |
fmt.Println("b[:5] :", b[:5]) | |
fmt.Println("b[:] :", b[:]) | |
x := b[:] | |
fmt.Println("x := b[:], print x:", x) | |
} | |
func sliceInternals() { | |
fmt.Println("the structure of an int") | |
colorPrint("[ len int ]", "green") | |
colorPrint("[ cap int ]", "yellow") | |
colorPrint("[ptr *Elem]", "red") | |
fmt.Printf(" └─>") | |
colorPrint("[0,0,0,0]", "red") | |
} | |
func colorPrint(str, clr string) { | |
switch clr { | |
case "red": | |
fmt.Printf("\033[91m%s\033[0m\n", str) | |
case "green": | |
fmt.Printf("\033[92m%s\033[0m\n", str) | |
case "yellow": | |
fmt.Printf("\033[93m%s\033[0m\n", str) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment