Just wanted to know what advantage we get using method than a regular funtion call

Hi All,

I am new learner to golang. On reading the structs, functions and method topic, Triggered a doubt.

We can pass a struct to a function as a argument than a method. Then why is significance of method in golang?? Can anyone explain with example

In simple terms Curious to know a case where, " A method can perform which is not possible to implement using function." or what benefit with method logic.

Sample code for method or function call using struct

package main

import (
“fmt”
)

type Person struct {
name string
age int
}

// Function takes struct argument
func functionCall(first Person) {
fmt.Println(“Normal Funtion call”, first)
}
//Method call on struct type
func (second Persoan) methodCall() {
fmt.Println(“Method Function call”, second)
}
func main() {
p1 := Person{“satish”, 23}
p1.name = “kumar”
functionCall(p1)
p1.name = “Yes”
p1.methodCall()
}
Output:
Normal Funtion call {kumar 23}
Method Function call {Yes 23}

Hi @satish_kumar,

From a functional point of view, a method defined for a type “T” is equivalent to a function with a parameter of type T. Both can do exactly the same operations on T.

However, methods allows to model a type that has one or more values and a particular behavior.

Example: a file type may have Read and Write methods.

And here is why methods are needed:

Go allows you to define “interface” types. An interfaces describes only a behavior without providing an implementation for that behavior.

Example: the io.ReadWriter interface declares Read and Write functions. Nowhere does the ReadWriter define any implementation. It only says, “I can read and write data to or from a data stream.”

Now because the aforementioned file type has Read and Write methods implemented, it can be substituted for the interface type.

How does this work?

A function can accept an interface type, such as io.ReadWriter. Now the function nows that the received actual argument must have Read and Write methods.

And then you can pass a variable of the file type to that function, even though the function has no idea what a “file” type is. All that the function knows is that the variable has the same Read and Write methods as declared by the interface type.

Now you can have more types that implement the same Read and Write methods, like a network connection type, a string type, a buffer type, a mock file type for testing, etc. You can substitute them all for the ReadWriter interface type, and the function can call Read and Write on any of that types.

In other words, you can abstract away the behavior of reading from and writing to a data stream from actual implementations of that behavior.

This would be impossible with only plain functions and passive types.

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