英文:
Go global variable and short variable definition
问题
在下面的代码片段中:
package ...
var Conn *sql.DB // 外部 Conn
func Init(user, pwd, dbname string, port int) {
Conn, err := sql.Open("postgres", "... args") // 内部 Conn
// ..
}
内部的 Conn 是一个新的变量,而 外部 的 Conn 将保持为空。
通过显式定义 err 并用赋值替换短变量定义,似乎可以正确初始化外部的 Conn 变量
var err error
Conn, err = sql.Open("postgres", "... args") // 内部 Conn
有没有更简单的方法来指定内部的 Conn 实际上不是一个作用域变量,而是全局的 Conn 变量?我在想是否有类似 package.Conn 的方式,但在包内部是无效的。
英文:
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.
答案1
得分: 6
不,就是这样。:=只是<strike>New()</strike>(https://golang.org/doc/effective_go.html#allocation_new)的快捷方式,用于变量声明(var foo int)。更符合惯用法(并且在一般情况下更好的设计)是返回连接而不使用全局变量。
func Init(user string, pwd string, dbname string, port int) (*sql.DB, error) {
// ...
}
依赖注入是你的朋友,请尽量不要破坏作用域。
英文:
Nope, that's it. := is just a shortcut to <strike>New() (https://golang.org/doc/effective_go.html#allocation_new)</strike> 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.
<!-- language: go -->
func Init(user string, pwd string, dbname string, port int) (*sql.DB, error) {
// ...
}
Dependency injection is your friend, try not to break scope.
答案2
得分: 5
不,这没有简写形式。:=总是将值赋给当前(最内层)作用域中的变量,如果需要的话会创建新的变量。要将值赋给当前作用域之外的任何变量,必须使用=而不是:=,而在多重赋值的情况下,这意味着所有变量必须预先声明。
英文:
No, there is no shorthand for this. := always assigns to variables in the current (innermost) scope, creating new variables if necessary. To assign to any variables outside the current scope, you must use = instead of :=, and in the case of multiple-assignment this means that all variables must be pre-declared.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论