Go語言之init函數(shù)
init函數(shù)會在main函數(shù)執(zhí)行之前進(jìn)行執(zhí)行、init用在設(shè)置包、初始化變量或者其他要在程序運(yùn)行前優(yōu)先完成的引導(dǎo)工作。
舉例:在進(jìn)行數(shù)據(jù)庫注冊驅(qū)動的時候。
這里有init函數(shù)
package postgres
package postgres
import (
"database/sql"
"database/sql/driver"
"errors"
)
// PostgresDriver provides our implementation for the
// sql package.
type PostgresDriver struct{}
// Open provides a connection to the database.
func (dr PostgresDriver) Open(string) (driver.Conn, error) {
return nil, errors.New("Unimplemented")
}
var d *PostgresDriver
// init is called prior to main.
func init() {
d = new(PostgresDriver)
sql.Register("postgres", d)
}這里是main函數(shù)
// Sample program to show how to show you how to briefly work
// with the sql package.
package main
import (
"database/sql"
_ "github.com/goinaction/code/chapter3/dbdriver/postgres"
)
// main is the entry point for the application.
func main() {
sql.Open("postgres", "mydb")
}可以看到這里main函數(shù)中使用看sql.Open 就是得益于上面的init函數(shù)
_ "github.com/goinaction/code/chapter3/dbdriver/postgres"
下劃線加上包名的作用就是,執(zhí)行這個包的init函數(shù)。
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
相關(guān)文章
實(shí)時通信的服務(wù)器推送機(jī)制 EventSource(SSE) 簡介附go實(shí)現(xiàn)示例代碼
EventSource是一種非常有用的 API,適用于許多實(shí)時應(yīng)用場景,它提供了一種簡單而可靠的方式來建立服務(wù)器推送連接,并實(shí)現(xiàn)實(shí)時更新和通知,這篇文章主要介紹了實(shí)時通信的服務(wù)器推送機(jī)制 EventSource(SSE)簡介附go實(shí)現(xiàn)示例,需要的朋友可以參考下2024-03-03
go語言實(shí)現(xiàn)mqtt協(xié)議的實(shí)踐
MQTT是一個基于客戶端-服務(wù)器的消息發(fā)布/訂閱傳輸協(xié)議。本文主要介紹了go語言實(shí)現(xiàn)mqtt協(xié)議的實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
Go語言函數(shù)的延遲調(diào)用(Deferred Code)詳解
本文將介紹Go語言函數(shù)和方法中的延遲調(diào)用,正如名稱一樣,這部分定義不會立即執(zhí)行,一般會在函數(shù)返回前再被調(diào)用,我們通過一些示例來了解一下延遲調(diào)用的使用場景2022-07-07

