Go语言之init函数
发布日期:2022-07-15 19:20 | 文章来源:源码中国
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函数。
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。
版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。
相关文章