Showing posts with label go. Show all posts
Showing posts with label go. Show all posts

Monday, May 3, 2021

Maps







package main

import "fmt"

func main() {
    colors := map[string]string{
        "red":   "#ff000",
        "green": "#4bf745",
    }

    fmt.Println(colors)
}


Different Ways of defining a Map

package main

import "fmt"

func main() {
    // var colors map[string]string

    colors := make(map[string]string)

    // colors := map[string]string{
    //  "red":   "#ff000",
    //  "green": "#4bf745",
    // }

    fmt.Println(colors)
}


Adding Values

colors["white"] = "#ffffff"


Deleting Values

    colors[10] = "#ffffff"

    delete(colors, 10)

    fmt.Println(colors)


Iterating over Maps


func printMap(c map[string]string) {
    for color, hex := range c {
        fmt.Println("Hex code for", color, "is", hex)
    }
}


Maps vs Structs

Sunday, May 2, 2021

Receivers

d is the instance. Similar to self in python,



Convention of instance is normally lowercase letters.

When to use a receiver?

  • It depends
  • You need to determine firsr the function signature
  • For example, if you want to execute instance.print() you must use a receiver
func (d deck) print() {
    for i, card := range d {
        fmt.Println(i, card)
    }
}

Other format

If the instance will not be used.


func (eb englishBot) getGreeting() string {
    return "Hi there!"
}


You can ommit the variable and do it this way.


func (englishBot) getGreeting() string {
    return "Hi there!"
}

Saturday, April 10, 2021

Writer interface does opposite of reader interface.








Function signature is similar to reader interface.





IO Copy




Example:

io.Copy(os.Stdout, resp.Body)


resp.Body - implements Reader interface (source)

os.Stdout - implements Writer interface (destination)





Monday, March 15, 2021

Interfaces

Purpose of Interfaces

Do we need different functions whose only difference is the type of values they receive? Hell no!


Thats the problem interfaces are solving.

Example

In order for a function or type to satisfy an interface, it must adhere with what the interface defined.


package main

import "fmt"

type bot interface {
    getGreeting() string
}

type englishBot struct{}
type spanishBot struct{}

func main() {
    eb := englishBot{}
    sb := spanishBot{}

    printGreeting(eb)
    printGreeting(sb)
}

func printGreeting(b bot) {
    fmt.Println(b.getGreeting())
}

func (englishBot) getGreeting() string {
    // very custom logic for generating english greeting
    return "Hi there!"
}

func (spanishBot) getGreeting() string {
    // very custom logic for generating spanish greeting
    return "Hola!"
}


Rules


NOTE Some interface in standard libraries has this format

Other information about interfaces


  • Implicit - no need to use keywords such as “extends” or “implements”