简体   繁体   中英

How to use Pointers correctly in Golang

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

Here is my program:

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

My questions are:

  • getVolume() should receive a pointer to Cube and RectangularPrism ?
  • Is there a better way of doing this?

Aim here is to right efficient code.

Thanks in advance

As defined in this https://golang.org/doc/faq#methods_on_values_or_pointers

if you are modifying data in the struct or handling huge amounts of data or if your struct is very huge its better to use a pointer.

as in the above cases, if you are passing it by the value it makes a difference as through each function call you pass a new copy of the struct which might affect your application's efficiency.

for very small data passing it by value or pointer won't make a difference as the difference would be negligible(like in your example it won't make a difference) https://play.golang.org/p/t3_Xzhq88g-

if you decide on a way to call function all your other functions will also have to be called in a similar fashion.

so analyse your use case (these are some suggestive uses cases there might be more scenarios)

1) are you gonna modify data in the struct

2) is the data gonna be huge

3) or if the struct is gonna be huge

4) are you gonna return the modified values (like in your example)

and based you these you can use a pointer or pass-by-value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM