【问题标题】:When to use pointer in methods and return pointers to structs? [duplicate]何时在方法中使用指针并返回指向结构的指针? [复制]
【发布时间】:2017-05-22 18:13:02
【问题描述】:

我正在努力学习围棋。我了解到结构和数组是按值复制的(将它们传递给函数或将它们分配给变量时)。所以我们使用指针来允许修改它们并节省内存。

问题是,在某些情况下,我总是发现它们使用指向结构的指针。

例如,在an official web application tutorial 他们使用了代码

 func (p *Page) save() error {
  filename := p.Title + ".txt"
  return ioutil.WriteFile(filename, p.Body, 0600)
 }

在这里,结构没有发生数据更改。这发生在官方包和第 3 方包中的其他地方。

另一种情况是它们返回 &struct{}。来自上述同一链接的示例:

 func loadPage(title string) *Page {
   filename := title + ".txt"
   body, _ := ioutil.ReadFile(filename)
   return &Page{Title: title, Body: body}
 }

那么,在哪些情况和地点应该使用指针呢?

【问题讨论】:

标签: go


【解决方案1】:

这是一个关于 go 的想法很酷,我们可以使用指针来节省内存使用。

在我的案例中,每当我从数据库中获取数据并想从中更改某些内容时,我都会使用指针。因此我使用指针来节省内存使用量。

例子:

func GetUserShopInfo(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
    //....
    shop_data, err := shop.GetUserShopInfo(user_id)
    // manipulate shop_data 
    shop.ChangeValue(&shop_data)
    // you will get the result here without creating new variable

}

然后我在想要共享值时使用指针,并更改它们而无需创建新变量来获得结果。

例子:

func main(){
    a := 10
    ChangeValue(&a)
    // a will change here
}    


func ChangeValue(a *int){
   // do something to a
}

结构体也是如此。我使用了指针,以便我可以传递和修改变量中的值

例子:

type Student struct {
    Human
    Schoool string
    Loan    float32
}

// use pointer so that we can modify the Loan value from previous
func (s *Student) BorrowMoney(amount float32) {
    s.Loan += amount
}

总之,每当我想分享价值时,我都会在每种情况下使用指针。

【讨论】:

  • 传递指针会使它们逃到堆中。对于可以在堆栈中廉价传递(按值传递)的小型结构,随着时间的推移,这可能会产生不必要的 GC 压力。这总是一个权衡。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 2012-10-09
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多