add: unfinished code. people are having problems

This commit is contained in:
Inanc Gumus
2018-11-13 17:43:25 +03:00
parent 67b20e5755
commit 490223331c
103 changed files with 4218 additions and 3 deletions

View File

@ -0,0 +1,25 @@
package main
import "fmt"
func main() {
var (
myAge byte
herAge byte
// uncomment the code below and observe the error
// wrongDeclaration [-1]byte
zero [0]byte
ages [2]byte
agesExp [2 + 1]byte
tags [5]string
)
fmt.Printf("%d %d\n", myAge, herAge)
fmt.Printf("%#v\n", zero)
fmt.Printf("%#v\n", ages)
fmt.Printf("%#v\n", agesExp)
fmt.Printf("%#v\n", tags)
}

View File

@ -0,0 +1,33 @@
package main
// STORY:
// Hipster's Love store publishes limited books
// twice a year.
//
// The number of books they publish is fixed at 4.
// So, let's create a 4 elements string array for the books.
const (
winter = 1
summer = 3
yearly = winter + summer
)
func main() {
// var books [4]string
// var books [1 + 3]string
var books [yearly]string
books[0] = "Kafka's Revenge"
books[1] = "Stay Golden"
books[2] = "Everythingship"
books[3] += books[0] + " 2nd Edition"
// Go compiler can catch indexing errors when constant is used
// books[4] = "Neverland"
// Go compiler cannot catch indexing errors when non-constant is used
// i := 4
// books[i] = "Neverland"
}

View File

@ -0,0 +1,74 @@
package main
import "fmt"
// STORY:
// Hipster's Love store publishes limited books
// twice a year.
//
// The number of books they publish is fixed at 4.
// So, let's create a 4 elements string array for the books.
const (
winter = 1
summer = 3
yearly = winter + summer
)
func main() {
var books [yearly]string
books[0] = "Kafka's Revenge"
books[1] = "Stay Golden"
books[2] = "Everythingship"
books[3] += books[0] + " 2nd Edition"
fmt.Printf("books : %#v\n", books)
// ------------------------------------
// SEASONAL BOOKS
// ------------------------------------
var (
wBooks [winter]string
sBooks [summer]string
)
// assign the first book as the wBook's first book
wBooks[0] = books[0]
// assign all the books starting from the 2nd book
// to sBooks array
// sBooks[0] = books[1]
// sBooks[1] = books[2]
// sBooks[2] = books[3]
// for i := 0; i < len(sBooks); i++ {
// sBooks[i] = books[i+1]
// }
for i := range sBooks {
sBooks[i] = books[i+1]
}
fmt.Printf("\nwinter : %#v\n", wBooks)
fmt.Printf("\nsummer : %#v\n", sBooks)
// ------------------------------------
// Let's print the published books
// ------------------------------------
// equal to: [4]bool
var published [len(books)]bool
published[0] = true
published[len(books)-1] = true
fmt.Println("\nPublished Books:")
for i, ok := range published {
if ok {
fmt.Printf("+ %s\n", books[i])
}
}
}

View File

@ -0,0 +1,57 @@
package main
import "fmt"
// STORY:
// Hipster's Love store publishes limited books
// twice a year.
//
// The number of books they publish is fixed at 4.
// So, let's create a 4 elements string array for the books.
const (
winter = 1
summer = 3
yearly = winter + summer
)
func main() {
// ALTERNATIVE:
// Use this only when you don't know about the elements beforehand
// var books [yearly]string
books := [yearly]string{
"Kafka's Revenge",
"Stay Golden",
"Everythingship",
"Kafka's Revenge 2nd Edition",
}
fmt.Printf("books : %#v\n", books)
// var (
// wBooks [winter]string
// sBooks [summer]string
// )
// wBooks[0] = books[0]
// for i := range sBooks {
// sBooks[i] = books[i+1]
// }
// fmt.Printf("\nwinter : %#v\n", wBooks)
// fmt.Printf("\nsummer : %#v\n", sBooks)
// var published [len(books)]bool
// published[0] = true
// published[len(books)-1] = true
// fmt.Println("\nPublished Books:")
// for i, ok := range published {
// if ok {
// fmt.Printf("+ %s\n", books[i])
// }
// }
}

View File

@ -0,0 +1,42 @@
package main
import "fmt"
// STORY:
// You want to compare two bookcases,
// whether they're equal or not.
func main() {
// When comparing two arrays,
// Their types should be identical
var (
// equal (types + elements are identical)::
blue = [3]int{6, 9, 3}
red = [3]int{6, 9, 3}
// equal (types + elements are identical):
// blue = [...]int{6, 9, 3}
// red = [3]int{6, 9, 3}
// not equal (element ordering are different):
// blue = [3]int{6, 9, 3}
// red = [3]int{3, 9, 6}
// not equal (the last elements are not equal):
// blue = [3]int{6, 9}
// red = [3]int{6, 9, 3}
// not comparable (type mismatch: length):
// blue = [3]int{6, 9, 3}
// red = [5]int{6, 9, 3}
// not comparable (type mismatch: element type):
// blue = [3]int64{6, 9, 3}
// red = [3]int{6, 9, 3}
)
fmt.Printf("blue bookcase : %v\n", blue)
fmt.Printf("red bookcase : %v\n", red)
fmt.Println("Are they equal?", blue == red)
}

View File

@ -0,0 +1,28 @@
package main
import "fmt"
// STORY:
// You want to compare two bookcases,
// whether they're equal or not.
func main() {
type (
bookcase [5]int
cabinet [5]int
)
blue := bookcase{6, 9, 3, 2, 1}
red := cabinet{6, 9, 3, 2, 1}
fmt.Print("Are they equal? ")
if cabinet(blue) == red {
fmt.Println("✅")
} else {
fmt.Println("❌")
}
fmt.Printf("blue: %#v\n", blue)
fmt.Printf("red : %#v\n", bookcase(red))
}

View File

@ -1 +0,0 @@
This section is in progress. I'm working hard to update the course all the time. Hold on!

View File

@ -0,0 +1,47 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args[1:]
var (
sum float64
nums [5]float64
)
for i, v := range args {
n, err := strconv.ParseFloat(v, 64)
if err != nil {
continue
}
nums[i] = n
sum += n
}
fmt.Println("Your numbers :", nums)
fmt.Println("Average :", sum/float64(len(nums)))
}
// EXERCISE
// Average calculator has a flaw.
// It divides the numbers by the length of the array.
// This results in wrong calculatio.
//
// For example:
//
// When you run it like this:
// go run main.go 1 5
// It tells you that the average number is:
// 1.2
// Whereas, actually, it should be 3.
//
// Fix this error.
// So that, it will output 3 instead of 1.2
//
// Do not change the length of the array.

View File

@ -0,0 +1,29 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args[1:]
var (
sum float64
nums []float64
)
for _, v := range args {
n, err := strconv.ParseFloat(v, 64)
if err != nil {
continue
}
nums = append(nums, n)
sum += n
}
fmt.Println("Your numbers:", nums)
fmt.Println("Average:", sum/float64(len(nums)))
}

View File

@ -0,0 +1,32 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args[1:]
var (
sum float64
nums [5]float64
total float64
)
for i, v := range args {
n, err := strconv.ParseFloat(v, 64)
if err != nil {
continue
}
total++
nums[i] = n
sum += n
}
fmt.Println("Your numbers:", nums)
fmt.Printf("(Only %g of them were valid)\n", total)
fmt.Println("Average:", sum/total)
}

View File

@ -0,0 +1,41 @@
package main
import (
"fmt"
"os"
"strconv"
)
const usage = `Sorry. Go arrays are fixed.
So, for now, I'm only supporting sorting %d numbers...
`
func main() {
args := os.Args[1:]
var nums [5]float64
if len(args) > 5 {
fmt.Printf(usage, len(nums))
return
}
for i, v := range args {
n, err := strconv.ParseFloat(v, 64)
if err != nil {
continue
}
nums[i] = n
}
for range nums {
for i, v := range nums {
if i < len(nums)-1 && v > nums[i+1] {
nums[i], nums[i+1] = nums[i+1], nums[i]
}
}
}
fmt.Println(nums)
}

View File

@ -0,0 +1,34 @@
package main
import (
"fmt"
"os"
"strings"
)
const corpus = `lazy cat jumps again and again and again...
since she is very excited and happy.`
func main() {
query := os.Args[1:]
words := strings.Fields(corpus)
filter := [...]string{
"and", "or", "the", "is", "since", "very",
}
queries:
for _, q := range query {
for _, v := range filter {
if q == v {
continue queries
}
}
for i, w := range words {
if q == w {
fmt.Printf("#%-2d: %q\n", i+1, w)
}
}
}
}

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"
func main() {
jake := "jake"
joe := "joe"
lee := "lee"
lina := "lina"
fmt.Println(jake)
fmt.Println(joe)
fmt.Println(lee)
fmt.Println(lina)
// for each name
// you need to declare a variable
// and then you need to print it
//
// but by using an array, you don't need to do that
}

View File

@ -0,0 +1,27 @@
// 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() {
// instead of storing the names in variables,
// you can use an array to store all of the names
// in a single variable
// names := [3]string{"jake", "joe", "lee"}
names := [4]string{"jake", "joe", "lee", "lina"}
// doing so allows you to loop over the names
// and print each one of them
//
// you can't do this without arrays
for _, name := range names {
fmt.Println(name)
}
}

View File

@ -0,0 +1,18 @@
// 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() {
ages := [3]int{15, 30, 25}
for _, age := range ages {
fmt.Println(age)
}
}

View File

@ -0,0 +1,18 @@
// 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
func main() {
// uncomment the code below to observe the error
// ages := [3]int{15, 30, 25, 44}
// for _, age := range ages {
// fmt.Println(age)
// }
}

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 "fmt"
func main() {
// you cannot use variables
// when setting the length of an array
// length := 3
// but, you can use constants and constant expressions
const length = 3 * 2
ages := [3 * 2]int{15, 30, 25}
for _, age := range ages {
fmt.Println(age)
}
}
// EXERCISE:
// Try to put the `length` constant
// in place of `3 * 2` above.
// EXERCISE:
// Try to put the `length` variable
// in place of `3 * 2` above.
//
// And observe the error.
//
// To do that, you need comment-out
// the length constant first.

View File

@ -0,0 +1,51 @@
// 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
func main() {
// -----
// you cannot use incompatible values
// than the array's element type
//
// uncomment the code parts below one by one
// then observe the errors
// -----
// for example you can't use a string
// ages := [3]int{15, 30, "hi"}
// -----
// or a float64, etc...
// ages := [3]int{15, 30, 5.5}
// -----
// of course this is valid, since it's untyped
// 5. becomes 5 (int)
// ages := [3]int{15, 30, 5.}
// -----
// for _, age := range ages {
// fmt.Println(age)
// }
}
// EXERCISE:
// Try to put the `length` constant
// in place of `3 * 2` above.
// EXERCISE:
// Try to put the `length` variable
// in place of `3 * 2` above.
//
// And observe the error.
//
// To do that, you need comment-out
// the length constant first.

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() {
ages := [...]int{15, 30, 25}
// equals to:
// ages := [3]int{15, 30, 25}
for _, age := range ages {
fmt.Println(age)
}
}

View File

@ -0,0 +1,22 @@
// 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() {
ages := [3]int{15, 30, 25}
fmt.Printf("%T\n", ages) // [3]int
fmt.Printf("%T\n", [...]int{15, 30, 25}) // [3]int
fmt.Printf("%T\n", [2]int{15, 30}) // [2]int
fmt.Printf("%T\n", [1]string{"hi"}) // [1]string
fmt.Printf("%T\n", [...]float64{3.14, 6.28}) // [2]float64
}

View File

@ -0,0 +1,16 @@
// 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 ages [3]int
fmt.Println(ages)
}

View File

@ -0,0 +1,16 @@
// 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() {
ages := [3]int{1}
fmt.Println(ages)
}

View File

@ -0,0 +1,18 @@
// 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{
"lina", "bob", "jane",
}
fmt.Printf("%#v\n", names)
}

View File

@ -0,0 +1,18 @@
// 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 := [5]string{
"lina", "bob", "jane",
}
fmt.Printf("%#v\n", names)
}

View File

@ -0,0 +1,21 @@
// 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 := [5]string{
"lina", "bob", "jane",
}
fmt.Printf("%#v\n", names)
temperatures := [10]float64{1.5, 2.5}
fmt.Printf("%#v\n", temperatures)
}

View File

@ -0,0 +1,35 @@
// 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() {
ages := [2]int{15, 20}
// i can directly use `len`
fmt.Println(len(ages)) // 2
// i can also assign its result to a variable
l := len(ages)
fmt.Println(l) // 2
// let's print the length of a few arrays
l = len([1]bool{true}) // 1
fmt.Println(l)
l = len([3]string{"lina", "james", "joe"}) // 3
fmt.Println(l)
// this array doesn't initialize any elements
// but its length is still 5
// whether the elements are initialized or not
l = len([5]int{})
fmt.Println(l) // 5
fmt.Println([5]int{})
}

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() {
ages := [2]int{15, 20}
// WRONG (try it):
// fmt.Println(ages[-1])
fmt.Println("1st item:", ages[0])
fmt.Println("2nd item:", ages[1])
// fmt.Println("2nd item:", ages[2])
// fmt.Println(ages[len(ages)])
// here, `len(ages) - 1` equals to 1
fmt.Println("last item:", ages[len(ages)-1])
// let's display the indexes and the items
// of the array
for i, v := range ages {
fmt.Printf("index: %d, value: %d\n", i, v)
}
}

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"
func main() {
ages := [2]int{15, 20}
ages[0] = 6
ages[1] *= 3
fmt.Println(ages)
// increase the last element by 1
ages[1]++
ages[len(ages)-1]++
fmt.Println(ages)
// v is a copy
for _, v := range ages {
// it's like:
// v = ages[0]
// v++
// and:
// v = ages[1]
// v++
v++
}
fmt.Println(ages)
// you don't need to use blank-identifier for the value
// for i, _ := range ages {
for i := range ages {
ages[i]++
}
fmt.Println(ages)
}

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() {
a := [3]int{6, 9, 3}
b := [3]int{6, 9, 3}
if a == b {
fmt.Println("they're equal!")
// they're comparable
// since their types are identical
fmt.Printf("1st array's type is %T\n", a)
fmt.Printf("2nd array's type is %T\n", b)
// go compares arrays like this
// it compares the elements one by one
fmt.Println(a[0] == b[0])
fmt.Println(a[1] == b[1])
fmt.Println(a[2] == b[2])
}
}

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 "fmt"
func main() {
a := [3]int{6, 9, 3}
b := [3]int{3, 9, 6}
if a == b {
fmt.Println("they're equal!")
} else {
fmt.Println("they're not equal! a==b?", a == b)
// but, they're comparable
// since their types are identical
fmt.Printf("1st array's type is %T\n", a)
fmt.Printf("2nd array's type is %T\n", b)
// go compares arrays like this
// it compares the elements one by one
fmt.Println(a[0] == b[0]) // false
fmt.Println(a[1] == b[1]) // true
fmt.Println(a[2] == b[2]) // false
// actually Go will quit comparing these arrays
// once it sees unequal items
//
// so, it will stop the comparison (short-circuit)
// when it sees the first item is false
// and it will return false
}
}

View File

@ -0,0 +1,24 @@
// 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
func main() {
// these two arrays not comparable
// their types are different
// uncomment all the code below and observe the error
// a := [3]int{6, 9, 3}
// b := [2]int{6, 9}
// you can't ask this question
// if a == b {
// fmt.Println("they're equal!")
// }
}

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() {
a := [2]string{"jane", "lina"}
b := [2]string{"jane", "lina"}
c := [2]string{"mike", "joe"}
fmt.Println("a==b?", a == b) // equal
fmt.Println("a==c?", a == c) // not equal
// cannot compare
d := [3]string{"jane", "lina"}
// fmt.Println("c==d?", c == d)
fmt.Printf("type of c is %T\n", c)
fmt.Printf("type of d is %T\n", d)
}

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() {
type (
A [3]int
B [3]int
)
x := A{1, 2, 3}
y := B{1, 2, 3}
z := [3]int{1, 2, 3}
fmt.Printf("x's type: %T\n", x) // named type : main.A
fmt.Printf("y's type: %T\n", y) // named type : main.B
fmt.Printf("z's type: %T\n", z) // unnamed type: [3]int
// cannot compare different named types
// fmt.Println("x==y?", x == y)
// can convert between identical types
fmt.Println("x==y?", x == A(y))
fmt.Println("x==y?", B(x) == y)
fmt.Printf("x's type : %T\n", x)
fmt.Printf("A(y)'s type: %T\n", A(y))
// can compare to unnamed types
fmt.Println("x==z?", x == z)
}

View File

@ -0,0 +1,24 @@
// 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() {
a := [3]int{5, 4, 7}
// this assignment will create a new array value
// and then it will be stored in the b variable
b := a
fmt.Println("a =>", a)
fmt.Println("b =>", b)
// they're equal, they're clones
fmt.Println("a==b?", a == b)
}

View File

@ -0,0 +1,27 @@
// 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() {
a := [3]int{5, 4, 7}
b := a
// this will only change the 'a' array
a[0] = 10
fmt.Println("a =>", a)
fmt.Println("b =>", b)
// this will only change the 'b' array
b[1] = 20
fmt.Println("a =>", a)
fmt.Println("b =>", b)
}

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 "fmt"
func main() {
a := [3]int{5, 4, 7}
b := [3]int{6, 9, 3}
b = a
fmt.Println("b =>", b)
b[0] = 100
fmt.Println("a =>", a)
fmt.Println("b =>", b)
}

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
func main() {
// you can't assign the array 'a' to the array 'b'
// a's type is [2]int whereas b's type is [3]int
// when two values are not comparable,
// then they're not assignable either
// uncomment and observe the error
// a := [2]int{5, 4}
// b := [3]int{6, 9, 3}
// b = a
}

View File

@ -0,0 +1,31 @@
// 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() {
a := [3]int{10, 4, 7}
// like the assignment passing an array to a function
// creates a copy of the array
fmt.Println("a (before) =>", a)
incr(a)
fmt.Println("a (after) =>", a)
}
// inside the function
// the passed array 'a' is a new copy (a clone)
// it's not the original one
func incr(a [3]int) {
// this only changes the copy of the passed array
a[1]++
// this prints the copied array not the original one
fmt.Println("a (inside) =>", a)
}

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"
func main() {
// [LENGTH]TYPE {
// ELEMENTS
// }
// LENGTH=2 and TYPE=[2]int
// nums := [2][2]int{
// [2]int{2, 4},
// [2]int{1, 3},
// }
// code below is the same as the code above
nums := [2][2]int{
{2, 4},
{1, 3},
}
fmt.Println("nums =", nums)
fmt.Println("nums[0] =", nums[0])
fmt.Println("nums[1] =", nums[1])
fmt.Println("nums[0][0] =", nums[0][0])
fmt.Println("nums[0][1] =", nums[0][1])
fmt.Println("nums[1][0] =", nums[1][0])
fmt.Println("nums[1][1] =", nums[1][1])
fmt.Println("len(nums) =", len(nums))
fmt.Println("len(nums[0]) =", len(nums[0]))
fmt.Println("len(nums[1]) =", len(nums[1]))
for i, array := range nums {
for j, n := range array {
// nums[i][j] = number
fmt.Printf("nums[%d][%d] = %d\n", i, j, n)
}
}
}

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() {
rates := [3]float64{
0.5,
2.5,
1.5,
}
fmt.Println(rates)
}

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"
func main() {
rates := [3]float64{
0: 0.5, // index: 0
1: 2.5, // index: 1
2: 1.5, // index: 2
}
fmt.Println(rates)
// above array literal equals to this:
//
// rates := [3]float64{
// 0.5,
// 2.5,
// 1.5,
// }
}

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"
func main() {
rates := [3]float64{
1: 2.5, // index: 1
0: 0.5, // index: 0
2: 1.5, // index: 2
}
fmt.Println(rates)
// above array literal equals to this:
//
// rates := [3]float64{
// 0.5,
// 2.5,
// 1.5,
// }
}

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"
func main() {
rates := [3]float64{
// index 0 empty
// index 1 empty
2: 1.5, // index: 2
}
fmt.Println(rates)
// above array literal equals to this:
//
// rates := [3]float64{
// 0.,
// 0.,
// 1.5,
// }
}

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() {
// ellipsis (...) below calculates the length of the
// array automatically
rates := [...]float64{
// index 0 empty
// index 1 empty
// index 2 empty
// index 3 empty
// index 4 empty
5: 1.5, // index: 5
}
fmt.Println(rates)
// above array literal equals to this:
//
// rates := [6]float64{
// 0.,
// 0.,
// 0.,
// 0.,
// 0.,
// 1.5,
// }
}

View File

@ -0,0 +1,34 @@
// 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() {
rates := [...]float64{
// index 1 to 4 empty
5: 1.5, // index: 5
2.5, // index: 6
0: 0.5, // index: 0
}
fmt.Println(rates)
// above array literal equals to this:
//
// rates := [7]float64{
// 0.5,
// 0.,
// 0.,
// 0.,
// 0.,
// 1.5,
// 2.5,
// }
}

View File

@ -0,0 +1,21 @@
// 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() {
rates := [...]float64{
25.5, // ethereum
120.5, // wanchain
}
// uses magic values - not good
fmt.Printf("1 BTC is %g ETH\n", rates[0])
fmt.Printf("1 BTC is %g WAN\n", rates[1])
}

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"
// REFACTORED VERSION
// It uses well-defined names instead of magic numbers.
// Thanks to keyed elements and constants.
func main() {
const (
ETH = iota
WAN
)
rates := [...]float64{
ETH: 25.5,
WAN: 120.5,
}
// uses well-defined names (ETH, WAN, ...) - good
fmt.Printf("1 BTC is %g ETH\n", rates[ETH])
fmt.Printf("1 BTC is %g WAN\n", rates[WAN])
}

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"
"math/rand"
"os"
"time"
)
func main() {
args := os.Args[1:]
if len(args) != 1 {
fmt.Println("[your name]")
return
}
name := args[0]
moods := [...]string{
"happy 😀", "good 👍", "awesome 😎",
"sad 😞", "bad 👎", "terrible 😩",
}
rand.Seed(time.Now().UnixNano())
n := rand.Intn(len(moods))
fmt.Printf("%s feels %s\n", name, moods[n])
}
// inspired from:
// https://github.com/moby/moby/blob/1fd7e4c28d3a4a21c3540f03a045f96a4190b527/pkg/namesgenerator/names-generator.go

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 (
"fmt"
"math/rand"
"os"
"time"
)
func main() {
args := os.Args[1:]
if len(args) != 2 {
fmt.Println("[your name] [positive|negative]")
return
}
name, mood := args[0], args[1]
moods := [...][3]string{
{"happy 😀", "good 👍", "awesome 😎"},
{"sad 😞", "bad 👎", "terrible 😩"},
}
rand.Seed(time.Now().UnixNano())
n := rand.Intn(len(moods[0]))
var mi int
if mood != "positive" {
mi = 1
}
fmt.Printf("%s feels %s\n", name, moods[mi][n])
}

View File

@ -0,0 +1,72 @@
// 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"
"strconv"
"time"
)
const (
maxTurns = 5 // less is more difficult
usage = `Welcome to the Lucky Number Game!
The program will pick %d random numbers.
Your mission is to guess one of those numbers.
The greater your number is, harder it gets.
Wanna play?
`
)
func main() {
rand.Seed(time.Now().UnixNano())
args := os.Args[1:]
if len(args) != 1 {
fmt.Printf(usage, maxTurns)
return
}
guess, err := strconv.Atoi(args[0])
if err != nil {
fmt.Println("Not a number.")
return
}
if guess < 0 {
fmt.Println("Please pick a positive number.")
return
}
// This array will store the generated random numbers
var pickeds [maxTurns]int
for turn := 0; turn < maxTurns; turn++ {
n := rand.Intn(guess + 1)
pickeds[turn] = n
if n == guess {
fmt.Println("🎉 YOU WIN!")
goto pickeds
}
}
fmt.Println("☠️ YOU LOST... Try again?")
pickeds:
fmt.Println("Computer has picked these:", pickeds)
// after this line the program automatically exits
}

View File

@ -0,0 +1,22 @@
// 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
// ?
//
// NOTE
// ?
//
// EXPECTED OUTPUT
// ?
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,11 @@
// 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
func main() {
}

View File

@ -0,0 +1,82 @@
// 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"
"strconv"
"time"
)
const (
maxTurns = 5 // less is more difficult
usage = `Welcome to the Lucky Number Game!
The program will pick %d random numbers.
Your mission is to guess one of those numbers.
The greater your number is, harder it gets.
Wanna play?
`
)
func main() {
rand.Seed(time.Now().UnixNano())
args := os.Args[1:]
if len(args) != 1 {
fmt.Printf(usage, maxTurns)
return
}
guess, err := strconv.Atoi(args[0])
if err != nil {
fmt.Println("Not a number.")
return
}
if guess < 0 {
fmt.Println("Please pick a positive number.")
return
}
// This array will store the generated random numbers
var pickeds [maxTurns]int
for turn := 0; turn < maxTurns; turn++ {
var n int
pick:
for {
n = rand.Intn(guess + 1)
for _, v := range pickeds {
if n == v {
continue pick
}
}
break
}
pickeds[turn] = n
if n == guess {
fmt.Println("🎉 YOU WIN!")
goto pickeds
}
}
fmt.Println("☠️ YOU LOST... Try again?")
pickeds:
fmt.Println("Computer has picked these:", pickeds)
// after this line the program automatically exits
}

View File

@ -0,0 +1,3 @@
## ?
* text *CORRECT*
* text

View File

@ -0,0 +1,16 @@
const (
Mon Weekday = iota
Tue
Wed
Thu
Fri
Sat
Sun
)
var names = [...]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
for d := Mon; d <= Sun; d++ {
fmt.Println(names[d])
}

View File

@ -0,0 +1,19 @@
package main
import "fmt"
func main() {
age1 := getAge(15)
age2 := getAge(25)
age3 := getAge(35)
fmt.Printf("age1 lives in %p\n", age1)
fmt.Printf("age2 lives in %p\n", age2)
fmt.Printf("age3 lives in %p\n", age3)
}
func getAge(n byte) *byte {
m := new(byte)
*m = n
return m
}

View File

@ -0,0 +1,36 @@
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
records := [...][3]string{
{"first_name", "last_name", "username"},
{"Rob", "Pike", "rob"},
{"Ken", "Thompson", "ken"},
{"Robert", "Griesemer", "gri"},
}
w := csv.NewWriter(os.Stdout)
for _, record := range records {
if err := w.Write(record[:]); err != nil {
log.Fatalln("error writing record to csv:", err)
}
}
// Write any buffered data to the underlying writer (standard output).
w.Flush()
if err := w.Error(); err != nil {
log.Fatal(err)
}
// Output:
// first_name,last_name,username
// Rob,Pike,rob
// Ken,Thompson,ken
// Robert,Griesemer,gri
}

View File

@ -0,0 +1,10 @@
# Array
## Summary
* An array can store any type of values as long as they've the same type
* Fixed Length and Type
* Stores the same type of values
* Array stores its values contagiously

View File

@ -0,0 +1,191 @@
package main
import (
"fmt"
"time"
)
// NOTE: We're going to refactor this code in the functions section.
const (
charDefault = "█"
charColon = "░"
charEmpty = " "
charSeparator = " "
// clears the screen
//
// only works on bash command prompts
// \033 is a control code: [2J clears the screen
//
// For Go Playground, use: "\f"
charClear = "\033[H\033[2J"
)
func main() {
// for keeping things easy to read and type-safe
type placeholder [5][3]byte
// we're using arrays because:
// - the pattern of a placeholder is constant (it doesn't change)
// - the placeholders in the clock is constant (which is 8)
//
// so, whenever values are precomputed or constant, use an array.
//
// you can always convert it to a slice easily. you'll learn
// how to do so in the slices section.
digits := [10]placeholder{
// 0
{
{1, 1, 1},
{1, 0, 1},
{1, 0, 1},
{1, 0, 1},
{1, 1, 1},
},
// 1
{
{1, 1, 0},
{0, 1, 0},
{0, 1, 0},
{0, 1, 0},
{1, 1, 1},
},
// 2
{
{1, 1, 1},
{0, 0, 1},
{1, 1, 1},
{1, 0, 0},
{1, 1, 1},
},
// 3
{
{1, 1, 1},
{0, 0, 1},
{1, 1, 1},
{0, 0, 1},
{1, 1, 1},
},
// 4
{
{1, 0, 1},
{1, 0, 1},
{1, 1, 1},
{0, 0, 1},
{0, 0, 1},
},
// 5
{
{1, 1, 1},
{1, 0, 0},
{1, 1, 1},
{0, 0, 1},
{1, 1, 1},
},
// 6
{
{1, 1, 1},
{1, 0, 0},
{1, 1, 1},
{1, 0, 1},
{1, 1, 1},
},
// 7
{
{1, 1, 1},
{0, 0, 1},
{0, 0, 1},
{0, 0, 1},
{0, 0, 1},
},
// 8
{
{1, 1, 1},
{1, 0, 1},
{1, 1, 1},
{1, 0, 1},
{1, 1, 1},
},
// 9
{
{1, 1, 1},
{1, 0, 1},
{1, 1, 1},
{0, 0, 1},
{1, 1, 1},
},
}
colon := placeholder{
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
}
// For Go Playground: loop 100 steps, for example.
for {
// get the current time: hour, minute, and second
var (
now = time.Now()
hour, min, sec = now.Hour(), now.Minute(), now.Second()
)
// again, an array is used here.
//
// because, the number of placeholders in this clock
// is constant (which is 8 placeholders).
clock := [8]placeholder{
// separate the digits: 17 becomes, 1 and 7 respectively
digits[hour/10], digits[hour%10],
colon,
digits[min/10], digits[min%10],
colon,
digits[sec/10], digits[sec%10],
}
fmt.Print(charClear)
// print the clock
for line := range clock[0] {
// print a line for each letter
for letter, v := range clock {
// colon blink
char := charDefault
if v == colon {
char = charEmpty
if sec%2 == 0 {
char = charColon
}
}
// print a line
for _, c := range clock[letter][line] {
if c == 1 {
fmt.Print(char)
} else {
fmt.Print(charEmpty)
}
}
fmt.Print(charSeparator)
}
fmt.Println()
}
// wait for 1 second
time.Sleep(time.Second)
}
}

View File

@ -0,0 +1,15 @@
package main
// ---------------------------------------------------------
// EXERCISE: Name
// ?
//
// NOTE
// ?
//
// EXPECTED OUTPUT
// ?
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,4 @@
package main
func main() {
}

View File

@ -0,0 +1,36 @@
package main
// ---------------------------------------------------------
// EXERCISE: Declare empty arrays
//
// 1. Declare and printf the following arrays:
//
// 1. A string array with 4 items
// 2. An int array 5 items
// 3. A byte array with 5 items
// 4. A float64 array with 1 item
// 5. A bool array with 4 items
// 6. A byte array without any items
//
// 2. Print the types of the previous arrays.
//
// NOTE
// You should use printf with #v verb.
//
// EXPECTED OUTPUT
// names : [4]string{"", "", "", ""}
// distances: [5]int{0, 0, 0, 0, 0}
// data : [5]uint8{0x0, 0x0, 0x0, 0x0, 0x0}
// ratios : [1]float64{0}
// switches : [4]bool{false, false, false, false}
// zero : [0]bool{}
// names : [4]string
// distances: [5]int
// data : [5]uint8
// ratios : [1]float64
// switches : [4]bool
// zero : [0]bool
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,36 @@
package main
import "fmt"
func main() {
// 1. Declare and printf the following arrays:
// 1. A string array with 4 items
// 2. An int array 5 items
// 3. A byte array with 5 items
// 4. A float64 array with 1 item
// 5. A bool array with 4 items
// 6. A byte array without any items
var (
names [4]string
distances [5]int
data [5]byte
ratios [1]float64
switches [4]bool
zero [0]bool
)
fmt.Printf("names : %#v\n", names)
fmt.Printf("distances: %#v\n", distances)
fmt.Printf("data : %#v\n", data)
fmt.Printf("ratios : %#v\n", ratios)
fmt.Printf("switches : %#v\n", switches)
fmt.Printf("zero : %#v\n", zero)
// 2. Print the types of the previous arrays.
fmt.Printf("names : %T\n", names)
fmt.Printf("distances: %T\n", distances)
fmt.Printf("data : %T\n", data)
fmt.Printf("ratios : %T\n", ratios)
fmt.Printf("switches : %T\n", switches)
fmt.Printf("zero : %T\n", zero)
}

View File

@ -0,0 +1,17 @@
package main
// search for books in hipster's love
// ---------------------------------------------------------
// EXERCISE: Name
// ?
//
// NOTE
// ?
//
// EXPECTED OUTPUT
// ?
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,40 @@
package main
import (
"fmt"
"os"
"strings"
)
const yearly = 4
func main() {
var books [yearly]string
books[0] = "Kafka's Revenge"
books[1] = "Stay Golden"
books[2] = "Everythingship"
books[3] += books[0] + " 2nd Edition"
if len(os.Args) != 2 {
fmt.Println("Tell me a book title")
return
}
query := os.Args[1]
fmt.Println("Search Results:")
fmt.Println("---------------")
var found bool
for _, v := range books {
if strings.Contains(strings.ToLower(v), query) {
fmt.Println("+", v)
found = true
}
}
if !found {
fmt.Printf("We don't have that book: %q\n", query)
}
}

View File

@ -0,0 +1,20 @@
# Array Exercises
1. **[Declare Empty Arrays](https://github.com/inancgumus/learngo/tree/master/14-arrays/exercises/01-declare-empty)**
- get data from command-line
- into a fixed array; see how it blows beyond its len
- add items
- get items
- check the length
- print the items
- reverse the array
- shuffle the items
- find the first item that contains x
- find the last item that contains y
- find the duplicate items
1. **[text](https://github.com/inancgumus/learngo/tree/master/)**
text

View File

@ -0,0 +1,64 @@
# Arrays
## Where is the 2nd variable below stored in memory?
```go
// Let's say that first variable below is stored in this memory location: 20th
var (
first int32 = 100
second int32 = 150
)
```
1. 21
2. 22
3. 24
4. It can be stored anywhere *CORRECT*
> **4:** That's right. It can be anywhere. Because, there's no guarantee that variables will be stored in contiguous memory locations.
## Where is the 3rd element of the following array stored in memory?
```go
//
// Let's say that:
// nums array is stored in this memory location (cell): 500th
//
// So, this means: nums[0] is stored at 500th location as well.
//
var nums [5]int64
```
1. 3
2. 2
3. 502
4. 503
5. 516 *CORRECT*
> **2:** Nope, that's the index of an element.
>
> **3, 4:** 500+index? You're getting closer.
>
> **5:** Perfect. Array elements are stored in contiguous memory locations (cells). Here, the array's location is 500, and each element is 8 bytes (int64). So, 1st element: 500th, 2nd element: 508th, 3rd element: 516th, and so on. Formula: 516 = 500 + (8 * (3 - 1)).
## How many values the following variable represents?
```go
var gophers [10]string
```
1. 0
2. 1 *CORRECT*
3. 2
4. 10
> **2:** That's right! A variable can only store one value. Here, it stores a single array value with all its elements. However, through the gophers variable, you can access to 10 string values individually of that array.
>
> **4:** That's the length of the array. It's not the number of values that the gophers variable represents.
## ?
1. text *CORRECT*
2. text
> **1:**
>

View File

@ -0,0 +1,34 @@
package main
import "fmt"
// STORY:
// Hipster's Love store publishes limited books
// twice a year.
//
// The number of books they publish is fixed at 4.
// So, let's create a 4 elements string array for the books.
const (
winter = 1
summer = 3
yearly = winter + summer
)
func main() {
var books [yearly]string
books[0] = "Kafka's Revenge"
books[1] = "Stay Golden"
books[2] = "Everythingship"
books[3] += books[0] + " 2nd Edition"
// won't update the original array
for _, v := range books {
v += " (Sold Out)"
fmt.Println(v)
}
fmt.Printf("\nbooks: %#v\n", books)
}

View File

@ -0,0 +1,45 @@
package main
import "fmt"
// STORY:
// Hipster's Love store publishes limited books
// twice a year.
//
// The number of books they publish is fixed at 4.
// So, let's create a 4 elements string array for the books.
const (
winter = 1
summer = 3
yearly = winter + summer
)
func main() {
var (
prevBooks [yearly]string
books [yearly]string
)
books[0] = "Kafka's Revenge"
books[1] = "Stay Golden"
books[2] = "Everythingship"
books[3] += books[0] + " 2nd Edition"
prevBooks = books
books[0] = "Silver Ages"
books[1] = "Dragon's Fire"
books[2] = "Nothingless"
books[3] = prevBooks[2] + " 2nd Edition"
fmt.Println("Last Year's Books (Sold Out!):")
for _, v := range prevBooks {
fmt.Println("+", v)
}
fmt.Println("\nNew Books:")
for _, v := range books {
fmt.Println("+", v)
}
}