Quantcast
Channel: 小惡魔 – 電腦技術 – 工作筆記 – AppleBOY
Viewing all articles
Browse latest Browse all 325

Go 語言的 init 函式

$
0
0
Go-brown-side.sh 本篇會帶大家認識 Go 語言的 init 函式,在了解 init func 之前,大家應該都知道在同一個 Package 底下是不可以有重複的變數或者是函式名稱,但是唯獨 init() 可以在同一個 package 內宣告多次都沒問題。底下看例子,可以發現的是不管宣告多少次,都會依序從最初宣告到最後宣告依序執行下來。
package main

import (
    "fmt"
)

func init() {
    fmt.Println("init 1")
}

func init() {
    fmt.Println("init 2")
}

func main() {
    fmt.Println("Hello, playground")
}

從其他 package 讀取 init func

有種狀況底下,主程式需要單獨讀取 package 內的 init func 而不讀取額外的變數,這時候就要透過 _ 來讀取 package。假設要讀取 lib/pq 內的 init,一定要使用 _
import(
    // Needed for the Postgresql driver
    _ "github.com/lib/pq
)
如果沒有加上 _,當編譯的時候就會報錯,原因就是 main 主程式內沒有用到 pq 內任何非 init() 的功能,所以不可編譯成功。如果有多個 package 的 init 需要同時引入,這邊也是會依照 import 的順序來讀取。

init 執行時機

大家一定很好奇 init 的執行時間是什麼時候,底下舉個例子
var global = convert()

func convert() int {
    return 100
}

func init() {
    global = 0
}

func main() {
    fmt.Println("global is", global)
}
或者是把 init() 放到最上面
func init() {
    global = 0
}

var global = convert()

func convert() int {
    return 100
}

func main() {
    fmt.Println("global is", global)
}
兩種結果都是 0,這邊大家就可以知,init 執行的時機會是在執行 main func 之前,所以不管前面做了哪些事情,都不會影響 init 的執行結果。最後提醒大家,只要 package 內有 init 的 func,在引入 package 時都會被執行。

線上影片


Go 語言線上課程目前特價 $1600,持續錄製中,每週都會有新的影片上架,歡迎大家參考看看,請點選底下購買連結:

點我購買


Viewing all articles
Browse latest Browse all 325

Trending Articles


Girasoles para colorear


mayabang Quotes, Torpe Quotes, tanga Quotes


Tagalog Quotes About Crush – Tagalog Love Quotes


OFW quotes : Pinoy Tagalog Quotes


Long Distance Relationship Tagalog Love Quotes


Tagalog Quotes To Move on and More Love Love Love Quotes


5 Tagalog Relationship Rules


Best Crush Tagalog Quotes And Sayings 2017


Re:Mutton Pies (lleechef)


FORECLOSURE OF REAL ESTATE MORTGAGE


Sapos para colorear


tagalog love Quotes – Tiwala Quotes


Break up Quotes Tagalog Love Quote – Broken Hearted Quotes Tagalog


Patama Quotes : Tagalog Inspirational Quotes


Pamatay na Banat and Mga Patama Love Quotes


Tagalog Long Distance Relationship Love Quotes


BARKADA TAGALOG QUOTES


“BAHAY KUBO HUGOT”


Vimeo 10.7.0 by Vimeo.com, Inc.


Vimeo 10.7.1 by Vimeo.com, Inc.