0

I'm new to golang. Just trying to understand the difference between the two methods declared for Calc type. The first function sum is declared as (c *Calc) Sum and the other one without * as (c Calc) Minus. What's the difference between the two and recommended way of writing this?

I see the difference comes in how we call the function under main. The point * type method requires new(Calc) and the other one can be called directly by doing Calc{}.Sum.

Some behavioural explanation will help.

   func main() {

    Calc{}.Minus(2, 2)
    c :=new(Calc)
    c.Sum(3, 2)
}


type Calc struct{
    Result int
}

func (c *Calc) Sum(a int, b int)  {
    c.Result = a + b
}

func (c Calc) Minus(a int, b int) {
    c.Result = a-b
}
Robin Kedia
  • 283
  • 3
  • 16
  • 3
    Hint: your `Minus` method does not _really_ update your instance of `Calc`. Can you figure out what's going on? (that's the main difference between them) – Sergio Tulentsev Jun 13 '19 at 00:00

1 Answers1

1

func (c *Calc) Sum(a int, b int) uses a pointer receiver, meaning any edit you make to c will change the variable it's called on.

func (c Calc) Minus(a int, b int) uses a value receiver. You can think of c in this instance as being only a copy of the variable it's called on. c.Result = a-b won't work as intended in this function.

It is operating on a copy of the variable and not a pointer to the variable

Vignoir
  • 21
  • 2