What is the difference between these functions?

First, I am noob at programming. Below are 2 similar functions made with different technique. (Parameters are on left and right) and these gives same result. In which case should I prefer one over the other?

type rectangle struct {
	a, b int
}

func display1(r rectangle) {
	fmt.Println("shapes=", r.a, "and", r.b)
}
func (r rectangle) display2() {
	fmt.Println("shapes=", r.a, "and", r.b)
}
func main() {
	a := rectangle{3, 5}
	b := rectangle{3, 5}
	display1(a)
	b.display2()

Hi @nextextr,

display1 is a function, and display2 is a method of struct rectangle. The “Parameters on the right” is actually not a parameter list but rather determines the “receiver” of the method. (See Method declarations - The Go Programming Language Specification)

They do exactly the same. The difference is that difference2 belongs to rectangle. Without display2, rectangle would be a simple struct. With display2, rectangle is a struct with a behavior. You can “request” the struct to display its values by calling b.display2().

The main advantage of methods is that you can group types and functions to form a type with a behavior. By looking at a type that has methods, you can instantly see what this type is made for, and how to use it. If there were no methods, you would only have types and “free” functions that happen to operate on that type.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.