• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Go中的Init函数

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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函数。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go结构体指针slice等发布时间:2022-07-12
下一篇:
go实现栈发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap