duanbai1370
2019-02-24 03:31
浏览 115
已采纳

在GoLang中按值传递或按引用传递更有效?

Let's say I have a struct implementing an interface like below:

type IFace interface {
   Method1()
   Method2()
   Method3()
} 


type Face struct {
  Prop1 string
  Prop2 int
}


// IFace implementation here...

Now if I have method that accepts IFace is it better to design it to accept a pointer to that interface of value?

  1. Accept pointer:
func DummyMethod(f *IFace) {
   (*f).Method1()
}
  1. By value:
    func DummyMethod(f IFace){
      f.Method1()
    }

My first guess is since these are structs, probably it's better to pass by value? Or is there a rule of thumb considering the size and nature of the struct when to start passing a pointer?

Also, when we are adding methods to a struct is it better to pass a pointer to the struct or it's value?

图片转代码服务由CSDN问答提供 功能建议

假设我有一个结构,实现了如下所示的接口:

 < 代码>类型IFace接口{
 Method1()
 Method2()
 Method3()
} 
 
 
type Face struct {
 Prop1字符串
 Prop2 int 
} 
 
 
  //此处是IFace的实现... 
   
 
 

现在,如果我有接受 IFace 的方法,最好将它设计为接受指针

  1. 接受指针:
      func DummyMethod(f *  IFace){
    (* f).Method1()
    } 
       
     
     
    1. 按值:
        func DummyMethod(f IFace){
       f.Method1()
      } 
         
       
       

      我的第一个猜测是,由于这些是结构,因此最好通过值传递? 还是有经验法则考虑何时开始传递指针的结构的大小和性质?

      此外,当我们向结构添加方法时,传递指针更好 到结构或它的值?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanbeng8872 2019-02-24 04:53
    已采纳

    When passing interface type as a parameter, pass it by value, note that interface type itself would be a pointer to concrete type.

    When it comes to the performance side, using interface comes with the price too, it simply cannot be inlined.

    I guess it is fine to use interface with dozen calls per request/entry point, but if an app has to make thousands+ invocations, benchmark your code first before making a call.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题