restructure: arrays and slices

This commit is contained in:
Inanc Gumus
2019-01-29 19:43:12 +03:00
parent 096ac9c251
commit c43d152d33
108 changed files with 92 additions and 243 deletions

View File

@@ -0,0 +1,30 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
{
// its length is part of its type
var nums [5]int
fmt.Printf("nums array: %#v\n", nums)
}
{
// its length is not part of its type
var nums []int
fmt.Printf("nums slice: %#v\n", nums)
fmt.Printf("len(nums) : %d\n", len(nums))
// won't work: the slice is nil.
// fmt.Printf("nums[0]: %d\n", nums[0])
// fmt.Printf("nums[1]: %d\n", nums[1])
}
}

View File

@@ -0,0 +1,38 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
var array [2]int
// zero value of an array is zero-valued elements
fmt.Printf("array : %#v\n", array)
// nope: arrays are fixed length
// array[2] = 0
var slice []int
// zero value of a slice is nil
fmt.Println("slice == nil?", slice == nil)
// nope: they don't exist:
// _ = slice[0]
// _ = slice[1]
// len function still works though
fmt.Println("len(slice) :", len(slice))
// array's length is part of its type
fmt.Printf("array's type: %T\n", array)
// whereas, slice's length isn't part of its type
fmt.Printf("slice's type: %T\n", slice)
}

View File

@@ -0,0 +1,52 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
// STORY:
// You want to list the books and games you have
func main() {
var books [5]string
books[0] = "dracula"
books[1] = "1984"
books[2] = "island"
newBooks := [5]string{"ulysses", "fire"}
if books == newBooks {
}
books = newBooks
games := []string{"kokemon", "sims"}
newGames := []string{"pacman", "doom", "pong"}
newGames = games
games = nil
games = []string{}
var ok string
for i, game := range games {
if game != newGames[i] {
ok = "not "
break
}
}
if len(games) != len(newGames) {
ok = "not "
}
fmt.Printf("games and newGames are %sequal\n\n", ok)
fmt.Printf("books : %#v\n", books)
fmt.Printf("new books : %#v\n", newBooks)
fmt.Printf("games : %T\n", games)
fmt.Printf("new games : %#v\n", newGames)
fmt.Printf("games's length: %d\n", len(games))
fmt.Printf("games's nil : %t\n", games == nil)
}

View File

@@ -0,0 +1,42 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
const max = 5
var uniques [max]int
// It's harder to make a program dynamic using arrays
// max, _ := strconv.Atoi(os.Args[1])
// var uniques [10]int
loop:
for found := 0; found < max; {
n := rand.Intn(max) + 1
fmt.Print(n, " ")
for _, u := range uniques {
if u == n {
continue loop
}
}
uniques[found] = n
found++
}
fmt.Println("\n\nuniques:", uniques)
}

View File

@@ -0,0 +1,56 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"math/rand"
"os"
"sort"
"strconv"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
max, _ := strconv.Atoi(os.Args[1])
// declare an uninitialized nil slice
var uniques []int
loop:
// you can still use the len function on a nil slice
for len(uniques) < max {
n := rand.Intn(max) + 1
fmt.Print(n, " ")
for _, u := range uniques {
if u == n {
continue loop
}
}
// append function can add new elements to a slice
uniques = append(uniques, n)
// a slice doesn't contain any elements right from the start
// uniques[found] = n
// found++
}
fmt.Println("\n\nuniques:", uniques)
fmt.Println("\nlength of uniques:", len(uniques))
sort.Ints(uniques)
fmt.Println("\nsorted:", uniques)
nums := [5]int{5, 4, 3, 2, 1}
sort.Ints(nums[:])
fmt.Println("\nnums:", nums)
}

View File

@@ -0,0 +1,39 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
s "github.com/inancgumus/prettyslice"
)
func main() {
nums := []int{1, 2, 3}
s.Show("nums", nums)
_ = append(nums, 4)
s.Show("nums", nums)
nums = append(nums, 4)
s.Show("nums", nums)
nums = append(nums, 9)
s.Show("nums", nums)
nums = append(nums, 4)
s.Show("nums", nums)
// or:
// nums = append(nums, 4, 9)
// s.Show("nums", nums)
nums = []int{1, 2, 3}
tens := []int{12, 13}
nums = append(nums, tens...)
s.Show("nums", nums)
}

View File

@@ -0,0 +1,33 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
s "github.com/inancgumus/prettyslice"
)
func main() {
var todo []string
todo = append(todo, "sing")
// you can only append elements with the same element type of the slice
// todo = append(todo, 42)
todo = append(todo, "run")
// append is a variadic function, so you can append multiple elements
todo = append(todo, "code", "play")
// you can also append a slice to another slice using ellipsis: ...
tomorrow := []string{"see mom", "learn go"}
todo = append(todo, tomorrow...)
// todo = append(todo, "see mom", "learn go")
s.Show("todo", todo)
}

View File

@@ -0,0 +1,38 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
s "github.com/inancgumus/prettyslice"
)
func main() {
msg := []byte{'h', 'e', 'l', 'l', 'o'}
s.Show("msg", msg)
s.Show("msg[0:1]", msg[0:1])
s.Show("msg[0:2]", msg[0:2])
s.Show("msg[0:3]", msg[0:3])
s.Show("msg[0:4]", msg[0:4])
s.Show("msg[0:5]", msg[0:5])
// default indexes
s.Show("msg[0:]", msg[0:])
s.Show("msg[:5]", msg[:5])
s.Show("msg[:]", msg[:])
// error: beyond
// s.Show("msg", msg)[:6]
s.Show("msg[1:4]", msg[1:4])
s.Show("msg[1:5]", msg[1:5])
s.Show("msg[1:]", msg[1:])
s.Show("append(msg)", append(msg[:4], '!'))
}

View File

@@ -0,0 +1,59 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
s "github.com/inancgumus/prettyslice"
)
func main() {
// think of this as search results of a search engine.
// it could have been fetched from a database
items := []string{
"pacman",
"mario",
"tetris",
"doom",
"galaga",
"frogger",
"asteroids",
"simcity",
"metroid",
"defender",
"rayman",
"tempest",
"ultima",
}
s.MaxPerLine = 4
s.Show("All items", items)
top3 := items[:3]
s.Show("Top 3 items", top3)
l := len(items)
// you can use variables in a slice expression
last4 := items[l-4:]
s.Show("Last 4 items", last4)
// reslicing: slicing another sliced slice
mid := last4[1:3]
s.Show("Last4[1:3]", mid)
// the same elements can be in different indexes
// fmt.Println(items[9], last4[0])
// slicing returns a slice with the same type of the sliced slice
fmt.Printf("slicing : %T %[1]q\n", items[2:3])
// indexing returns a single element with the type of the indexed slice's element type
fmt.Printf("indexing: %T %[1]q\n", items[2])
}

View File

@@ -0,0 +1,49 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
s "github.com/inancgumus/prettyslice"
)
func main() {
// think of this as search results of a search engine.
// it could have been fetched from a database
items := []string{
"pacman", "mario", "tetris", "doom",
"galaga", "frogger", "asteroids", "simcity",
"metroid", "defender", "rayman", "tempest",
"ultima",
}
// s.Show("0:4", items[0:4])
// s.Show("4:8", items[4:8])
// s.Show("8:12", items[8:12])
// s.Show("12:13", items[12:13])
// s.Show("12:14", items[12:14]) // error
l := len(items)
const pageSize = 4
for from := 0; from < l; from += pageSize {
to := from + pageSize
if to > l {
to = l
}
// fmt.Printf("%d:%d\n", from, to)
currentPage := items[from:to]
head := fmt.Sprintf("Page #%d", (from/pageSize)+1)
s.Show(head, currentPage)
}
}

8
16-slices/README.md Normal file
View File

@@ -0,0 +1,8 @@
# WARNING
For the code in this section, you should install my prettyslice library.
## STEPS
1. Open your command-line
2. Type: `go get -u github.com/inancgumus/prettyslice`
3. That's all.

View File

@@ -0,0 +1,38 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE: Declare nil slices
//
// 1. Declare the following slices as nil slices:
//
// 1. The names of your friends (names slice)
//
// 2. The distances to locations (distances slice)
//
// 3. A data buffer (data slice)
//
// 4. Currency exchange ratios (ratios slice)
//
// 5. Up/Down status of web servers (alives slice)
//
//
// 2. Print their type, length and whether they're equal to nil value or not.
//
//
// EXPECTED OUTPUT
// names : []string 0 true
// distances: []int 0 true
// data : []uint8 0 true
// ratios : []float64 0 true
// alives : []bool 0 true
// ---------------------------------------------------------
func main() {
}

View File

@@ -0,0 +1,26 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
var (
names []string // The names of your friends
distances []int // The distances
data []byte // A data buffer
ratios []float64 // Currency exchange ratios
alives []bool // Up/Down status of web servers
)
fmt.Printf("names : %T %d %t\n", names, len(names), names == nil)
fmt.Printf("distances: %T %d %t\n", distances, len(distances), distances == nil)
fmt.Printf("data : %T %d %t\n", data, len(data), data == nil)
fmt.Printf("ratios : %T %d %t\n", ratios, len(ratios), ratios == nil)
fmt.Printf("alives : %T %d %t\n", alives, len(alives), alives == nil)
}

View File

@@ -0,0 +1,41 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
// ---------------------------------------------------------
// EXERCISE: Assign empty slices
//
// Assign empty slices to all the slices that you've declared in the previous
// exercise, and print them here.
//
//
// EXPECTED OUTPUT
// names : []string 0 false
// distances: []int 0 false
// data : []uint8 0 false
// ratios : []float64 0 false
// alives : []bool 0 false
// ---------------------------------------------------------
func main() {
var (
names []string // The names of your friends
distances []int // The distances
data []byte // A data buffer
ratios []float64 // Currency exchange ratios
alives []bool // Up/Down status of web servers
)
fmt.Printf("names : %T %d %t\n", names, len(names), names == nil)
fmt.Printf("distances: %T %d %t\n", distances, len(distances), distances == nil)
fmt.Printf("data : %T %d %t\n", data, len(data), data == nil)
fmt.Printf("ratios : %T %d %t\n", ratios, len(ratios), ratios == nil)
fmt.Printf("alives : %T %d %t\n", alives, len(alives), alives == nil)
}

View File

@@ -0,0 +1,32 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
var (
names []string // The names of your friends
distances []int // The distances
data []byte // A data buffer
ratios []float64 // Currency exchange ratios
alives []bool // Up/Down status of web servers
)
names = []string{}
distances = []int{}
data = []byte{}
ratios = []float64{}
alives = []bool{}
fmt.Printf("names : %T %d %t\n", names, len(names), names == nil)
fmt.Printf("distances: %T %d %t\n", distances, len(distances), distances == nil)
fmt.Printf("data : %T %d %t\n", data, len(data), data == nil)
fmt.Printf("ratios : %T %d %t\n", ratios, len(ratios), ratios == nil)
fmt.Printf("alives : %T %d %t\n", alives, len(alives), alives == nil)
}

View File

@@ -0,0 +1,63 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
// ---------------------------------------------------------
// EXERCISE: Assign slice literals
//
// 1. Assign the following data using slice literals to the slices that
// you've declared in the first exercise.
//
// 1. The names of your best three friends (to the names slice)
//
// 2. The distances to five different locations (to the distances slice)
//
// 3. Five bytes of data (to the data slice)
//
// 4. Two currency exchange ratios (to the ratios slice)
//
// 5. Up/Down status of four different web servers (to the alives slice)
//
// 2. Print their type, length and whether they're equal to nil value or not
//
// 3. Compare the length of the distances and the data slices; print a message
// if they are equal (use an if statement).
//
//
// EXPECTED OUTPUT
// names : []string 3 false
// distances: []int 5 false
// data : []uint8 5 false
// ratios : []float64 2 false
// alives : []bool 4 false
// The length of the distances and the data slices are the same.
// ---------------------------------------------------------
func main() {
var (
names []string // The names of your friends
distances []int // The distances
data []byte // A data buffer
ratios []float64 // Currency exchange ratios
alives []bool // Up/Down status of web servers
)
names = []string{}
distances = []int{}
data = []byte{}
ratios = []float64{}
alives = []bool{}
fmt.Printf("names : %T %d %t\n", names, len(names), names == nil)
fmt.Printf("distances: %T %d %t\n", distances, len(distances), distances == nil)
fmt.Printf("data : %T %d %t\n", data, len(data), data == nil)
fmt.Printf("ratios : %T %d %t\n", ratios, len(ratios), ratios == nil)
fmt.Printf("alives : %T %d %t\n", alives, len(alives), alives == nil)
}

View File

@@ -0,0 +1,36 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
var (
names []string // The names of your friends
distances []int // The distances
data []byte // A data buffer
ratios []float64 // Currency exchange ratios
alives []bool // Up/Down status of web servers
)
names = []string{"serpil", "ebru", "lina"}
distances = []int{100, 200, 300, 400, 500}
data = []byte{'I', 'N', 'A', 'N', 'C'}
ratios = []float64{3.14, 6.28}
alives = []bool{true, false, false, true}
fmt.Printf("names : %T %d %t\n", names, len(names), names == nil)
fmt.Printf("distances: %T %d %t\n", distances, len(distances), distances == nil)
fmt.Printf("data : %T %d %t\n", data, len(data), data == nil)
fmt.Printf("ratios : %T %d %t\n", ratios, len(ratios), ratios == nil)
fmt.Printf("alives : %T %d %t\n", alives, len(alives), alives == nil)
if len(distances) == len(data) {
fmt.Println("The length of the distances and the data slices are the same.")
}
}

View File

@@ -0,0 +1,44 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
// ---------------------------------------------------------
// EXERCISE: Declare the arrays as slices
//
// 1. First run the following program as it is
//
// 2. Then change the array declarations to slice declarations
//
// 3. Observe whether anything changes or not (on the surface :)).
//
// EXPECTED OUTPUT
// names : []string ["Einstein" "Tesla" "Shepard"]
// distances: []int [50 40 75 30 125]
// data : []uint8 [72 69 76 76 79]
// ratios : []float64 [3.14]
// alives : []bool [true false true false]
// zero : []uint8 []
// ---------------------------------------------------------
func main() {
names := [3]string{"Einstein", "Tesla", "Shepard"}
distances := [...]int{50, 40, 75, 30, 125}
data := [5]byte{'H', 'E', 'L', 'L', 'O'}
ratios := [1]float64{3.14145}
alives := [...]bool{true, false, true, false}
zero := [0]byte{}
fmt.Printf("names : %[1]T %[1]q\n", names)
fmt.Printf("distances: %[1]T %[1]d\n", distances)
fmt.Printf("data : %[1]T %[1]d\n", data)
fmt.Printf("ratios : %[1]T %.2[1]f\n", ratios)
fmt.Printf("alives : %[1]T %[1]t\n", alives)
fmt.Printf("zero : %[1]T %[1]d\n", zero)
}

View File

@@ -0,0 +1,26 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
names := []string{"Einstein", "Tesla", "Shepard"}
distances := []int{50, 40, 75, 30, 125}
data := []byte{'H', 'E', 'L', 'L', 'O'}
ratios := []float64{3.14145}
alives := []bool{true, false, true, false}
zero := []byte{}
fmt.Printf("names : %[1]T %[1]q\n", names)
fmt.Printf("distances: %[1]T %[1]d\n", distances)
fmt.Printf("data : %[1]T %[1]d\n", data)
fmt.Printf("ratios : %[1]T %.2[1]f\n", ratios)
fmt.Printf("alives : %[1]T %[1]t\n", alives)
fmt.Printf("zero : %[1]T %[1]d\n", zero)
}

View File

@@ -0,0 +1,57 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE: Fix the problems
//
// 1. Uncomment the code
//
// 2. Fix the problems
//
// 3. BONUS: Simplify the code
//
//
// EXPECTED OUTPUT
// "Einstein and Shepard and Tesla"
// ["Fire" "Kafka's Revenge" "Stay Golden"]
// [1 2 3 5 6 7 8 9]
// ---------------------------------------------------------
func main() {
// var names []string
// names := []string{}
// names = [...]string{
// "Einstein" "Shepard"
// "Tesla"
// }
// -----------------------------------
// var books []string = [3]string{
// "Stay Golden",
// "Fire",
// "Kafka's Revenge",
// }
// sort.Strings(books)
// -----------------------------------
// // this time, do not change the nums array to a slice
// nums := [...]int{5,1,7,3,8,2,6,9}
// // use the slicing expression to change the nums array to a slice below
// sort.Ints(nums)
// -----------------------------------
// Here: Use the strings.Join function to join the names
// (see the expected output)
// fmt.Printf("%q\n", names)
// fmt.Printf("%q\n", books)
// fmt.Printf("%d\n", nums)
}

View File

@@ -0,0 +1,28 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
names := []string{"Einstein", "Shepard", "Tesla"}
books := []string{"Stay Golden", "Fire", "Kafka's Revenge"}
sort.Strings(books)
nums := [...]int{5, 1, 7, 3, 8, 2, 6, 9}
sort.Ints(nums[:])
fmt.Printf("%q\n", strings.Join(names, " and "))
fmt.Printf("%q\n", books)
fmt.Printf("%d\n", nums)
}

View File

@@ -0,0 +1,38 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE: Compare the slices
//
// 1. Split the namesA string and get a slice
//
// 2. Sort all the slices
//
// 3. Compare whether the slices are equal or not
//
//
// EXPECTED OUTPUT
//
// They are equal.
//
//
// HINTS
//
// 1. strings.Split function splits a string and
// returns a string slice
//
// 2. Comparing slices: First check whether their length
// are the same or not; only then compare them.
//
// ---------------------------------------------------------
func main() {
// namesA := "Da Vinci, Wozniak, Carmack"
// namesB := []string{"Wozniak", "Da Vinci", "Carmack"}
}

View File

@@ -0,0 +1,33 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
namesA := "Da Vinci, Wozniak, Carmack"
namesB := []string{"Wozniak", "Da Vinci", "Carmack"}
namesC := strings.Split(namesA, ", ")
sort.Strings(namesC)
sort.Strings(namesB)
if len(namesC) == len(namesB) {
for i := range namesC {
if namesC[i] != namesB[i] {
return
}
}
fmt.Println("They are equal.")
}
}

View File

@@ -0,0 +1,25 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append
//
// Please follow the instructions within the code below.
//
// EXPECTED OUTPUT
// They are equal.
//
// HINTS
// bytes.Equal function allows you to compare two byte
// slices easily. Check its documentation: go doc bytes.Equal
// ---------------------------------------------------------
func main() {
// 1. uncomment the code below
// png, header := []byte{'P', 'N', 'G'}, []byte{}
// 2. append elements to header to make it equal with the png slice
// 3. compare the slices using the bytes.Equal function
// 4. print whether they're equal or not
}

View File

@@ -0,0 +1,23 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"bytes"
"fmt"
)
func main() {
png, header := []byte{'P', 'N', 'G'}, []byte{}
header = append(header, png...)
if bytes.Equal(png, header) {
fmt.Println("They are equal")
}
}

View File

@@ -0,0 +1,41 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append #2
//
// 1. Create the following nil slices:
// + Pizza toppings
// + Departure times
// + Student graduation years
// + On/off states of lights in a room
//
// 2. Append them some elements (use your creativity!)
//
// 3. Print all the slices
//
//
// EXPECTED OUTPUT
// (Your output may change, mine is like so:)
//
// pizza : [pepperoni onions extra cheese]
//
// graduations : [1998 2005 2018]
//
// departures : [2019-01-28 15:09:31.294594 +0300 +03 m=+0.000325020
// 2019-01-29 15:09:31.294594 +0300 +03 m=+86400.000325020
// 2019-01-30 15:09:31.294594 +0300 +03 m=+172800.000325020]
//
// lights : [true false true]
//
//
// HINTS
// + For departure times, use the time.Time type. Check its documentation.
//
// now := time.Now() -> Gives you the current time
// now.Add(time.Hour*24) -> Gives you a time.Time 24 hours after `now`
//
// + For graduation years, you can use the int type
// ---------------------------------------------------------
func main() {
}

View File

@@ -0,0 +1,55 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"time"
)
func main() {
// ------------------------------------------------------------
// Create nil slices
// ------------------------------------------------------------
// Pizza toppings
var pizza []string
// Departure times
var departures []time.Time
// Student graduation years
var grads []int
// On/off states of lights in a room
var lights []bool
// ------------------------------------------------------------
// Append them some elements (use your creativity!)
// ------------------------------------------------------------
pizza = append(pizza, "pepperoni", "onions", "extra cheese")
now := time.Now()
departures = append(departures,
now,
now.Add(time.Hour*24), // 24 hours after `now`
now.Add(time.Hour*48)) // 48 hours after `now`
grads = append(grads, 1998, 2005, 2018)
lights = append(lights, true, false, true)
// ------------------------------------------------------------
// Print the slices
// ------------------------------------------------------------
fmt.Printf("pizza : %s\n", pizza)
fmt.Printf("\ngraduations : %d\n", grads)
fmt.Printf("\ndepartures : %s\n", departures)
fmt.Printf("\nlights : %t\n", lights)
}

View File

@@ -0,0 +1,27 @@
package main
// ---------------------------------------------------------
// EXERCISE: Append #3 — Fix the problems
//
// Fix the problems in the code below.
//
// BONUS
//
// Simplify the code.
//
// EXPECTED OUTPUT
//
// toppings: [black olives green peppers onions extra cheese]
//
// ---------------------------------------------------------
func main() {
// toppings := []int{"black olives", "green peppers"}
// var pizza [3]string
// append(pizza, ...toppings)
// pizza = append(toppings, "onions")
// toppings = append(pizza, extra cheese)
// fmt.Printf("pizza : %s\n", pizza)
}

View File

@@ -0,0 +1,20 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
toppings := []string{"black olives", "green peppers"}
var pizza []string
pizza = append(pizza, toppings...)
pizza = append(pizza, "onions", "extra cheese")
fmt.Printf("toppings: %s\n", pizza)
}

View File

@@ -0,0 +1,25 @@
# Slice Exercises
## Exercises Level I - Basics — Warm-Up
1. **[Declare nil slices](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/01-declare-nil)**
2. **[Assign empty slices](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/02-empty)**
3. **[Assign slice literals](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/03-slice-literal)**
4. **[Declare the arrays as slices](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/04-declare-arrays-as-slices)**
5. **[Fix the Problems](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/05-fix-the-problems)**
6. **[Compare the slices](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/06-compare-the-slices)**
---
## Exercises Level II - Appending
1. **[Append #1 — Append and compare byte slices](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/07-append)**
2. **[Append #2 — Append to a nil slice](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/08-append-2)**
3. **[Append #3 — Fix the problems](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/09-append-3-fix)**

View File

@@ -0,0 +1,123 @@
# Slices vs Arrays Quiz
## Why you want to use a slice instead of an array?
1. I like arrays more
2. I want to create a dynamic collection, so I need an array
3. A slice's length is dynamic, so I can create dynamic collections *CORRECT*
## Where does the length of a slice belong to?
1. Compile-Time
2. Runtime *CORRECT*
3. Walk-Time
4. Sleep-Time
> **2:** A slice's length is not a part of its type. So its length can change at runtime.
## Which function call below is correct?
```go
// Let's say there's a function like this.
func sort(nums []int) {
// ...
}
```
1. sort([...]int{3, 1, 6})
2. sort([]int32{3, 1, 6})
3. sort([]int{3, 1, 6}) *CORRECT*
> **1:** You can't call the sort function using an array. It expects an int slice.
>
> **2:** You can't call the sort function using an int32 slice. It expects an int slice.
>
> **3:** That's right! You can pass an int slice to the sort function.
## What is the zero value of this slice?
```go
var tasks []string
```
1. 0
2. 1
3. nil *CORRECT*
4. unknown
> **3:** This is a nil slice. Unlike an array, a slice's zero value is nil.
## What does this code print?
```go
var tasks []string
fmt.Println(len(tasks))
```
1. 0 *CORRECT*
2. 1
3. nil
4. It doesn't work.
> **1:** Yes, you can use the len function on a nil slice. It returns 0 because the slice doesn't contain any elements yet.
## What does this code print?
```go
var tasks []string
fmt.Println(tasks[0])
```
1. 0
2. 1
3. nil
4. It doesn't work. *CORRECT*
> **4:** You can't get an element that does not exist. A nil slice does not contain any elements.
## Which declaration below is a correct slice declaration?
1. [...]int{}
2. [2]string{"hello", "world"}
3. []string{"hello", "world"} *CORRECT*
4. string[2]{"hello", world"}
## This code doesn't work, why?
```go
colors := []string{"red", "blue", "green"}
tones := []string{"dark", "light"}
if colors == tones {
// ...
}
```
1. The slices have different lengths
2. If statement doesn't contain any statements
3. Slices cannot be compared *CORRECT*
> **3:** That's right! A slice value can only be compared to a nil value.
## What is the length of this slice?
```go
[]uint64{}
```
1. 64
2. 1
3. 0 *CORRECT*
4. Error
> **3:** That's right. This is an empty slice, it doesn't contain any elements.
## What is the length of this slice?
```go
[]string{"i'm", "going", "to", "stay", "\"here\""}
```
1. 0
2. 1
3. 2
4. 3
5. 4
6. 5 *CORRECT*

View File

@@ -0,0 +1,66 @@
# Appending Quiz
## How does the append function work?
1. It appends new elements to the given slice on the fly and returns a new slice, normally, it doesn't change the given slice *CORRECT*
2. It appends new elements to the given slice and returns the existing slice
3. It appends new elements to the given slice and returns a new slice, it also changes the given slice
> **1:** Yes, the append function doesn't change the given slice unless you overwrite the result of the append function back to the original slice. Most of the times, this is true.
>
> **2:** It doesn't return the existing slice, it returns a new slice. That's why you usually save the result of the append back to the original slice.
>
> **3:** It doesn't change the given slice, it creates and returns a new slice. Most of the times, this is true.
## When you call the append function, where does it append the new elements?
1. It appends them at the beginning of the given slice
2. It appends them at the middle of the given slice
3. It appends them after the length of the given slice *CORRECT*
> **3:** Yes! The append function appends the new elements by looking at the length of the given slice and then returns a new slice with the newly appended elements.
## What's the problem with the following code?
```go
nums := []int{9, 7, 5}
append(nums, []int{2, 4, 6}...)
fmt.Println(nums[3])
```
1. It can't append to an int slice
2. It can't append a slice to another slice
3. It tries to get an element that doesn't exist yet *CORRECT*
> **3:** That's right. The append function returns a new slice with the newly added elements. But here, the code doesn't save the result of the append, so the nums slice only has 3 elements. So, `nums[3]` is invalid, because there are only 3 elements in the nums slice.
## What does this program print?
```go
nums := []int{9, 7, 5}
evens := append(nums, []int{2, 4, 6}...)
fmt.Println(nums, evens)
```
1. [9 7 5] [2 4 6]
2. [9 7 5] [9 7 5 2 4 6] *CORRECT*
3. [9 7 5 2 4 6] [2 4 6]
4. [9 7 5 2 4 6] [9 7 5 2 4 6]
> **2:** It appends the new elements to the nums slice but it saves the returned slice to the evens slice. So, the nums slice doesn't change. That's why, it prints the original elements from the nums slice first, then it prints the evens slice with the newly added elements.
>
> **3, 4:** It doesn't save the result of the append call back into the nums slice, so the nums slice doesn't contain the new elements.
## What does this program print?
```go
nums := []int{9, 7, 5}
nums = append(nums, 2, 4, 6)
fmt.Println(nums)
```
1. [9 7 5 2 4 6] *CORRECT*
2. [9 7 5]
3. [2 4 6]
4. [2 4 6 9 7 5]
> **1:** It overwrites the nums slice with the new slice that is returned from the append function. So the nums slice has got the newly appended elements.

View File

@@ -0,0 +1,5 @@
# Slice Quizzes
* [Slices vs Arrays](1-slices-vs-arrays.md)
* [Appending](2-appending.md)