我是go
语言的新手,我的程序可以使用,但是不确定我是否应该使用指针。
这是我的程序:
package main
import (
"fmt"
"math"
)
type Shape interface {
getVolume() float64
}
type Cube struct {
Side float64
}
type RectanglePrism struct {
Length float64
Width float64
Height float64
}
func main() {
c := Cube{Side: 3}
r := RectanglePrism{Length: 4, Width: 3, Height: 3}
fmt.Println(Volume(c))
fmt.Println(Volume(r))
}
func (c Cube) getVolume() float64 {
return math.Pow(c.Side, 3)
}
func Volume(s Shape) float64 {
return s.getVolume()
}
func (r RectanglePrism) getVolume() float64 {
return r.Length * r.Width * r.Height
}
游乐场:https://play.golang.org/p/LKSvJXNCEbQ
如您所见,
Volume
不会修改c
中的值,只是进行计算,因此不一定需要将指向原始值-尽管如此,它仍会执行复制操作我的问题是:
getVolume()
应该接收指向Cube
和RectangularPrism
的指针吗? 这里的目标是正确的高效代码。
提前致谢
最佳答案
如本https://golang.org/doc/faq#methods_on_values_or_pointers中所定义
如果要在结构中修改数据或处理大量数据,或者结构非常庞大,则最好使用指针。
与上述情况一样,如果通过值传递它,则会有所不同,因为通过每个函数调用,您传递的是结构的新副本,这可能会影响应用程序的效率。
对于非常小的数据,通过值或指针传递它不会有什么区别,因为差异可以忽略(就像您的示例中那样,不会有区别)https://play.golang.org/p/t3_Xzhq88g-
如果您决定调用函数的方式,则所有其他函数也必须以类似的方式进行调用。
因此,请分析您的用例(这些是一些建议性的用例,可能会有更多场景)
1)您是否要修改结构中的数据
2)数据会很大吗
3)或结构会很大
4)您是否要返回修改后的值(例如您的示例)
根据这些,您可以使用指针或传递值
关于go - 如何在Golang中正确使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61410736/