英文:
How to remove duplicate ORM instantiation in Golang Beego
问题
在Golang应用程序模型中,
我有以下代码:
func AddClub(name string) int64 {
o := orm.NewOrm()
club := Club{Name: name}
id, err := o.Insert(&club)
if err != nil {
fmt.Printf("Id: %s, Error: %s", id, err)
}
return id
}
func GetAllClubs() []*Club {
o := orm.NewOrm()
var clubs []*Club
num, err := o.QueryTable("clubs").All(&clubs)
if err != nil {
fmt.Printf("Returned Rows Num: %s, %s", num, err)
}
return clubs
}
我想消除o := orm.NewOrm()
实例化的重复。我该如何做?
我尝试将其放在init()
函数的一部分中,如下所示:
func init() {
o := orm.NewOrm()
}
但是我在控制台上得到了未定义的o
错误。
英文:
In Golang application model
I have below:
func AddClub(name string) int64 {
o := orm.NewOrm()
club := Club{Name: name}
id, err := o.Insert(&club)
if err != nil {
fmt.Printf("Id: %s, Error: %s", id, err)
}
return id
}
Then below:
func GetAllClubs() []*Club {
o := orm.NewOrm()
var clubs []*Club
num, err := o.QueryTable("clubs").All(&clubs)
if err != nil {
fmt.Printf("Returned Rows Num: %s, %s", num, err)
}
return clubs
}
I want to remove duplication of o := orm.NewOrm()
instantiation. How do I do this?
I tried to put it as part of init()
func like below:
func init() {
o := orm.NewOrm()
}
But I get undefined o error in console
答案1
得分: 1
如果你想定义一个在整个包中都可用的变量,你需要在包级别声明它(如果你不打算注入它)。也就是说,在任何函数之外。
你也不能使用简写的 :=
进行初始化 - 必须是显式的。
因此,它必须是这样的:
var o orm.Ormer
func init() {
o = orm.NewOrm()
}
注意它是在函数之外声明的,并且它不使用简写的初始化和赋值运算符 :=
。
英文:
If you want to define a variable that is available for the entire package .. you need to declare it at the package level (if you're not going to be injecting it). That is, outside of any functions.
You also cannot use the shorthand :=
initialization for this - it must be explicit.
Therefore it must be something like:
var o orm.Ormer
func init() {
o = orm.NewOrm()
}
Notice that it is declared outside of the function, and it doesn't use the shorthand initialization and assignment operator :=
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论