package main
import "fmt"
/*
* Function to print the contents of an integer slice. Prints the
* first parameter as a label, then the contents of the slice on one row.
*/
func psl(s string, sl []int) {
fmt.Printf("%s: ", s)
for i := 0 ; i < len(sl) ; i++ {
fmt.Printf("%2d ", sl[i])
}
fmt.Println()
}
func main() {
// An array, a slice, and a demonstration of append.
arr := [10]int{1,2,3,4,5,6,7,8,9,10}
sl1 := arr[1:4]
sl2 := append(sl1, 20,21,22)
arr[3] = 99
// Line 'em up and have a look. The values are appended to
// the slice, but actually stored in the underlying array.
psl("sl1 a", sl1)
psl("sl2 a", sl2)
psl("arr a", arr[:])
fmt.Println()
// Now what about bounds?
sl1 = arr[7:10]
sl2 = append(sl1, 30,31,32)
arr[8] = 199
psl("sl1 b", sl1)
psl("sl2 b", sl2)
psl("arr b", arr[:])
fmt.Println()
// Notice: Append will allocate a new array if it needs
// more space.
// Okay. Lets give the array a clean value.
arr = [10]int{10,9,8,7,6,5,4,3,2,1}
psl("sl1 c", sl1)
psl("sl2 c", sl2)
psl("arr c", arr[:])
// The changes to arr track in sl1, but not in sl2, since
// that's referring to a different array.
fmt.Println()
// Copy function
sl1 = arr[2:5]
sl2 = arr[6:10]
copy(sl1,sl2)
psl("sl1 d", sl1)
psl("sl2 d", sl2)
psl("arr d", arr[:])
// Copy copies data from one slice to another, stopping when
// the destination slice is full. These data are stored in the
// underlying array.
}