日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Go語(yǔ)言之init函數(shù)_Golang

作者:奮斗的大橙子 ? 更新時(shí)間: 2022-09-04 編程語(yǔ)言

init函數(shù)會(huì)在main函數(shù)執(zhí)行之前進(jìn)行執(zhí)行、init用在設(shè)置包、初始化變量或者其他要在程序運(yùn)行前優(yōu)先完成的引導(dǎo)工作。

舉例:在進(jìn)行數(shù)據(jù)庫(kù)注冊(cè)驅(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ù)。

原文鏈接:https://www.cnblogs.com/dcz2015/p/10103220.html

欄目分類
最近更新