lundi 8 juillet 2019

Golang design pattern: assigning result of method calls to variables

I am coding in Golang and curious on what is the best practice when it comes to saving the result of a method call vs. making the method call over and over again.

In the example below, if I have to use area many times, should I assign it to a variable? Or is it purely style preference and really does not matter?

package main

import "fmt"

type rect struct {
    width, height int
}

func (r *rect) area() int {
    return r.width * r.height
}

func main() {
    r := rect{width: 10, height: 5}

    fmt.Println("area: ", r.area())
    fmt.Println("area: ", r.area())
    fmt.Println("area: ", r.area())
    fmt.Println("area: ", r.area())
    fmt.Println("area: ", r.area())

    // or 
    area := r.area()
    fmt.Println("area: ", area)
    fmt.Println("area: ", area)
    fmt.Println("area: ", area)
    fmt.Println("area: ", area)
    fmt.Println("area: ", area)
}

Aucun commentaire:

Enregistrer un commentaire