如何在Golang中正确使用指针

I am new to the go language and am in a scenario where my program works but not sure whether I should have use pointers or not.

这是我的程序:

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
}

Playground: https://play.golang.org/p/LKSvJXNCEbQ

As you can see Volume does not modify values in c, just does a calculation and therefore it doesn't necessarily need to point to the original value - nonetheless it does a copy which is more expensive

我的问题是:

  • getVolume() should receive a pointer to Cube and RectangularPrism?
  • if so, then how can I create getVolume() with a generic pointer? If this make sense.
  • Is there a better way of doing this?

这里的目标是正确的高效代码。

提前致谢

评论