如果你知道要返回的类型,你还会使用输出参数吗?

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

If you know the type you're returning, would you still use output arguments?

问题

很多Go代码使用以下模式:

var foo Foo
err := db.LoadFooByID(id, &foo)
// 使用加载的foo

这种模式有其优点,特别是在涉及事先不知道类型(interface{})的情况下。然而,如果你已经知道类型,在其他语言中,你会像这样使用LoadFooByID

foo, err := db.LoadFooByID(id)
// 使用加载的foo

然而,人们仍然更喜欢前一种模式。

我知道这个问题非常主观,但如果你必须提供一个在已知类型的情况下在整个代码库中一致应用的通用解决方案,你会选择哪个?

英文:

A lot of Go code uses the following pattern:

var foo Foo
err := db.LoadFooByID(id, &foo)
// use the loaded foo

This pattern has its merits, especially, when it comes to a type you don't know in advance (interface{}). However, if you already know the type, it any other language, you would use LoadFooByID like this:

foo, err := db.LoadFooByID(id)
// use the loaded foo

And yet, people still prefer the former pattern.

I know that the question is very subjective, but if you had to provide a generic case solution that you apply consistently across your code base (for known types), which one would you go for?

答案1

得分: 6

在第一种形式中,它接受一个指针,这使您有可能重用现有的Foo变量,避免生成"垃圾"。对于单个Foo来说无关紧要,但如果您在循环中加载Foo,可能会有所不同:您可以在所有迭代中使用单个Foo变量。

如果您有第一种形式,您总是可以创建一个辅助函数,提供第二种形式的功能:

func loadFooById(id int) (*Foo, error) {
    var foo Foo
    err := db.LoadFooByID(id, &foo)
    return &foo, err
}

如果您有第二种形式,您无法将其"转换"为第一种形式:如果LoadFooByID()函数是分配新的Foo的函数,您无法使其重用现有的Foo

英文:

In the first form that takes a pointer, that gives you the possibility to reuse an existing Foo variable, preventing you from generating "garbage". It doesn't matter for a single Foo, but if you're loading Foos in a loop, it might make a difference: you may use a single Foo variable in all iterations.

If you have the first form, you can always create a helper function that provides the functionality of the second form:

func loadFooById(id int) (*Foo, error) {
    var foo Foo
    err := db.LoadFooByID(id, &foo)
    return &foo, err
}

If you have the second form, you can't "convert" it to the first: if the LoadFooByID() function is the one allocating a new Foo, you can't make it reuse an existing one.

huangapple
  • 本文由 发表于 2021年10月8日 16:37:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/69492909.html
匿名

发表评论

匿名网友

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

确定