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

學無先后,達者為師

網站首頁 編程語言 正文

Go語言之init函數_Golang

作者:奮斗的大橙子 ? 更新時間: 2022-09-04 編程語言

init函數會在main函數執行之前進行執行、init用在設置包、初始化變量或者其他要在程序運行前優先完成的引導工作。

舉例:在進行數據庫注冊驅動的時候。

這里有init函數

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函數

// 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函數中使用看sql.Open 就是得益于上面的init函數

_ "github.com/goinaction/code/chapter3/dbdriver/postgres"

下劃線加上包名的作用就是,執行這個包的init函數。

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

欄目分類
最近更新