reorganize: interfaces section

This commit is contained in:
Inanc Gumus
2019-08-21 20:38:38 +03:00
parent 8cb42216e4
commit c282da3c6d
27 changed files with 126 additions and 20 deletions

View File

@ -15,6 +15,5 @@ type book struct {
}
func (b book) print() {
// b is a copy of the original `book` value here.
fmt.Printf("%-15s: $%.2f \n", b.title, b.price)
}

View File

@ -14,6 +14,9 @@ type game struct {
price float64
}
// be consistent:
// if another method in the same type has a pointer receiver,
// use pointer receivers on the other methods as well.
func (g *game) print() {
fmt.Printf("%-15s: $%.2f\n", g.title, g.price)
}
@ -27,8 +30,7 @@ func (g *game) discount(ratio float64) {
// PREVIOUS CODE:
// ----------------------------------------------------------------------------
// + `g` is a copy: `discount` cannot change the original `g`.
// func (g game) discount(ratio float64) {
// func (g *game) discount(ratio float64) {
// g.price *= (1 - ratio)
// }

View File

@ -0,0 +1,29 @@
// 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"
)
type huge struct {
// about ~200mb
games [10000000]game
}
// only copies a single pointer.
func (h *huge) addr() {
fmt.Printf("%p\n", h)
}
// each time it is called,
// the original value will be copied.
// calling addr() x 10 times = ~2 GB.
// func (h huge) addr() {
// fmt.Printf("%p\n", &h)
// }

View File

@ -1,26 +0,0 @@
// 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"
// + you can attach methods to any concrete type.
// + rule: you need to declare a new type in the same package.
type list []game
func (l list) print() {
// `list` acts like a `[]game`
if len(l) == 0 {
fmt.Println("Sorry. Our store is closed. We're waiting for the delivery 🚚.")
return
}
for _, it := range l {
it.print()
}
}

View File

@ -9,19 +9,22 @@ package main
func main() {
var (
// mobydick = book{title: "moby dick", price: 10}
mobydick = book{title: "moby dick", price: 10}
minecraft = game{title: "minecraft", price: 20}
tetris = game{title: "tetris", price: 5}
)
var items []game
items = append(items, minecraft, tetris)
// sends a pointer of minecraft to the discount method
// same as: (&minecraft).discount(.1)
minecraft.discount(.1)
// you can attach methods to a compatible type on the fly:
my := list([]game{minecraft, tetris})
mobydick.print()
minecraft.print()
tetris.print()
// you can call methods even on a nil value
// my = nil
my.print() // or: list.print(items)
// creates a variable that occupies 200mb on memory
var h huge
for i := 0; i < 10; i++ {
h.addr()
}
}