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

在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问答提供 功能建议

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

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

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

  1. 接受指针:</ li> </ ol>
      func DummyMethod(f *  IFace){
    (* f).Method1()
    } 
     </ code> </ pre> 
     
     
    1. 按值:</ li> </ ol>
        func DummyMethod(f IFace){
       f.Method1()
      } 
       </ code> </ pre> 
       
       

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

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

1条回答 默认 最新

相关推荐 更多相似问题