kok202
[2019.03.08] Go lang (Map, Defer, Panic, Recover)

2019. 3. 8. 18:28[공부] 영상/GoLanguage

Map

map[string]int 는 참조 타입이므로 make를 해줘야한다.

make(map[string]int)

package main

import "fmt"

func main() {
    grades := make(map[string]int)
    grades["math"] = 90
    grades["korean"] = 85
    grades["english"] = 80
    fmt.Println(grades)
    fmt.Println(grades["korean"])
    for class, grade := range grades {
        fmt.Println(class, " : ", grade)
    }
}








defer

= 함수가 어떤 방식으로 끝나든 일단 끝나면 한다. 

= 함수를 한번 감싸서 끝나는 시점에 호출함

package main

import "fmt"

func foo() {
    defer fmt.Println("call 2")
    defer fmt.Println("call 1")
    fmt.Println("call 0")
}

func main() {
    foo()
}


call 0
call 1
call 2








Panic

package main

func main() {
    for i := 0; i < 5; i++ {
        if i == 3 {
            panic("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        }
    }
}


panic: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

goroutine 1 [running]:
main.main()
/Users/-/Desktop/Project/Workspace_Golang/golang14_panic/golang.go:6 +0x58
exit status 2








Recover

package main

import "fmt"

func cleanup() {
    r := recover()
    if r != nil {
        fmt.Println("Recover exist, there might be panic : ", r)
    }
}

func main() {
    defer cleanup()
    for i := 0; i < 5; i++ {
        if i == 3 {
            panic("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        }
    }
}


Recover exist, there might be panic : !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!