iT邦幫忙

2021 iThome 鐵人賽

DAY 4
1
Modern Web

還喝不 go系列 第 4

[13th][Day4] defer fallthrough

  • 分享至 

  • twitterImage
  •  

defer 延遲執行
Golang 有個很方便的東東:defer,他執行的時間點會是在離開目前的 function 時

不過這裡需要注意的是有兩個地方:

變數的傳遞,會在呼叫defer的時候傳入.所以他並非單純的直接移到最後呼叫
根據 GoDoc Defer:

> The arguments to the deferred function (which include the receiver if the function is a 
> method) are evaluated when the defer executes.

那麼 defer 要用在何處呢?記得 defer 的特性是在函式 return 前執行,而且『一定會』被執行

package main

import (
    "fmt"
    "os"
)

func main() {
    f, err := os.Open("/src/ironman/D4/test.md")
    if err != nil {
        fmt.Println(err)
    } else {
        b1 := make([]byte, 5)
        n1, err := f.Read(b1)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Printf("%d bytes: %s\n", n1, string(b1))
            // 處理讀取的內容....
            f.Close()
        }
    }
}

這是一個讀取檔案的例子

os.Open()
f.Read()
上面的兩個 func 都匯回傳兩個值,第二個值 err 代表的是 func 執行中是否發生錯誤,因此程式中進行了錯誤的檢查,在沒有錯誤的情況下才進行檔案的讀取與內容處理,而最後透過

f.Close()
關閉檔案。

defer 是用來宣告 function 結束前的動作。

然而,有時候我們會想傳入值給 deferred function,此時分成兩種狀況:

使用 defer 宣告時的變數值
使用 deferred function 執行時的變數值
在寫程式,我們常犯一種低級錯誤,就是要了資源,but ... 沒有釋放。

以讀取檔案來舉例:你 fopen 了檔案,卻沒有 fclose

如何降低錯誤率?盡量減少 fopen 和 fclose 之間的距離,越近越好。最好是 fopen 完就呼叫 fclose ,這樣犯錯的可能性就降低很多了。

defer 是非常非常好用 而且很多情境下必須使用的東西


fallthrough

go 中的 fallthrough 使用方法

golang 的 switch 『默認』每個 case 最後都自帶 break,執行完成後會跳出整個 switch 不會向下執行

(如果有寫過其他的程式語言,嘗試不要在 switch 中,不寫 break 看看,看這個 switch 到底有沒有什麼用)

使用 fallthrough 可以強致執行後面的case
它只能用作 case 子句的最後面。

func main() {
	switch "Bond" {
	case "Moneypenny":
		fmt.Println("this should not print")
		fallthrough
	case "BBBB":
		fmt.Println("this should not print2")
		fallthrough
	case "Bond":
		fmt.Println("this should not print3")
		fallthrough	
	case "CC":
		fmt.Println("this should not print4")
		fallthrough
	default:
		fmt.Println("this is default")
	}
}

不能在最後一個 case 加上 fallthrough,會噴出錯誤
//scannot fallthrough final case in switch

golang 的 fallthrough 會『強制』執行後面的 case ,fallthrough 『不會判斷』下一則 case 的 true / false。


上一篇
[13th][Day3] 保留字
下一篇
[13th][Day5] Goroutine
系列文
還喝不 go23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言