如何在Golang Beego中删除重复的ORM实例化?

huangapple go评论63阅读模式
英文:

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 :=.

huangapple
  • 本文由 发表于 2015年1月12日 17:51:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/27899171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定