Sunday, June 23, 2024
HomeGolangWhat's the distinction between these capabilities? - Getting Assist

What’s the distinction between these capabilities? – Getting Assist

First, I’m noob at programming. Beneath are 2 comparable capabilities made with totally different approach. (Parameters are on left and proper) and these provides identical outcome. Through which case ought to I favor one over the opposite?

kind 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 essential() {
	a := rectangle{3, 5}
	b := rectangle{3, 5}

Hello @nextextr,

display1 is a perform, and display2 is a technique of struct rectangle. The “Parameters on the suitable” is definitely not a parameter record however moderately determines the “receiver” of the tactic. (See Technique declarations – The Go Programming Language Specification)

They do precisely the identical. The distinction is that difference2 belongs to rectangle. With out display2, rectangle could be a easy struct. With display2, rectangle is a struct with a habits. You’ll be able to “request” the struct to show its values by calling b.display2().

The principle benefit of strategies is you can group sorts and capabilities to type a sort with a habits. By a sort that has strategies, you may immediately see what this sort is made for, and the right way to use it. If there have been no strategies, you’d solely have sorts and “free” capabilities that occur to function on that kind.

1 Like

This matter was robotically closed 90 days after the final reply. New replies are now not allowed.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments