去全局变量和短变量定义 [英] Go global variable and short variable definition

查看:125
本文介绍了去全局变量和短变量定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码片段中:

$ $ p $ $ code $ package

var Conn * sql.DB / /外部Conn

func Init(用户,pwd,dbname字符串,端口int){
Conn,err:= sql.Open(postgres,... args)/ / inner conn
// ..
}

内部 Conn 是一个新变量,而 outer Conn 将保持为空。

通过显式定义 err 并用赋值来替换短变量定义,它似乎正确地初始化外部 Conn
$ pre $ var $ er $ error
conn,err = sql.Open(postgres,.. 。args)//内部Conn

是否有更简单的方法来指定内部 Conn 不应该是一个范围变量,而应该是全局 Conn 变量?我正在考虑像 package.Conn 这样的内容,但是它在包本身内部是无效的。

解决方案

不,就是这样。 := 只是 New()( https://golang.org/doc/effective_go.html#allocation_new 变量声明(var foo int)。一个更习惯的方法(和更好的设计一般)是返回连接,而不是使用全局变量。
$ b $ p
func Init (用户字符串,pwd字符串,dbname字符串,端口int)(* sql.DB,错误){
}



依赖注入是你的朋友,尽量不要打破范围。


In the following snippet

package ...

var Conn *sql.DB // outer Conn

func Init(user, pwd, dbname string, port int) {
    Conn, err := sql.Open("postgres", "... args") // inner Conn
    // ..
}

the inner Conn is a new variable and outer Conn will remain null.

By explicitly defining err and replacing the short variable definition with assignment it seems to properly init the outer Conn variable

    var err error
    Conn, err = sql.Open("postgres", "... args") // inner Conn

Is there a simpler way to specify the inner Conn should not really be a scoped variable but instead the global Conn variable? I'm thinking something like package.Conn, but that's invalid inside the package itself.

解决方案

Nope, that's it. := is just a shortcut to New() (https://golang.org/doc/effective_go.html#allocation_new) variable declaration (var foo int). A more idiomatic approach (and better design in general) is to return the connection and not to use global variables.

func Init(user string, pwd string, dbname string, port int) (*sql.DB, error) { }

Dependency injection is your friend, try not to break scope.

这篇关于去全局变量和短变量定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆