Go語言之init函數(shù)
init函數(shù)會在main函數(shù)執(zhí)行之前進行執(zhí)行、init用在設(shè)置包、初始化變量或者其他要在程序運行前優(yōu)先完成的引導(dǎo)工作。
舉例:在進行數(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)文章
實時通信的服務(wù)器推送機制 EventSource(SSE) 簡介附go實現(xiàn)示例代碼
EventSource是一種非常有用的 API,適用于許多實時應(yīng)用場景,它提供了一種簡單而可靠的方式來建立服務(wù)器推送連接,并實現(xiàn)實時更新和通知,這篇文章主要介紹了實時通信的服務(wù)器推送機制 EventSource(SSE)簡介附go實現(xiàn)示例,需要的朋友可以參考下2024-03-03
Go語言函數(shù)的延遲調(diào)用(Deferred Code)詳解
本文將介紹Go語言函數(shù)和方法中的延遲調(diào)用,正如名稱一樣,這部分定義不會立即執(zhí)行,一般會在函數(shù)返回前再被調(diào)用,我們通過一些示例來了解一下延遲調(diào)用的使用場景2022-07-07

