Go語言之init函數(shù)
init函數(shù)會在main函數(shù)執(zhí)行之前進(jìn)行執(zhí)行、init用在設(shè)置包、初始化變量或者其他要在程序運(yùn)行前優(yōu)先完成的引導(dǎo)工作。
舉例:在進(jìn)行數(shù)據(jù)庫注冊驅(qū)動(dòng)的時(shí)候。
這里有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í)行這個(gè)包的init函數(shù)。
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對本站的支持。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信