Published on

Methods in Go (with Example)

Methods in Go (with Example)

Go: Methods Explained

Methods are functions that are attached to a specific type. They are used to manipulate the values of that type and to provide an easy way to reuse code. In Go, methods are declared using the func keyword followed by the receiver type, which is the type the method will be attached to.

How to create Methods in Go

To create a method in Go, you first need to define the type you want to attach the method to. This can be done using a struct or an interface. Once the type is defined, you can create the method by defining the receiver type followed by the method name and the arguments you want to pass in. Here is an example:


type Person struct {
	Name string
	Age int
}

func (p *Person) SayHello() {
	fmt.Println("Hello, my name is", p.Name)
}

In this example, we have defined a struct named Person that contains two fields, Name and Age. We have then created a method named SayHello that is attached to the Person type. The method takes no arguments and simply prints a greeting.

How to use Methods in Go?

To use a method in Go, you first need to create an instance of the type the method is attached to. Once you have the instance, you can call the method by using the dot notation. Here is an example:


p := Person{Name: "John", Age: 30}
p.SayHello()

In this example, we have created an instance of the Person type and stored it in the p variable. We have then called the SayHello method on the p instance, which prints the greeting.

Method Overloading in Go

Method overloading is not supported in Go, which means that you cannot have two methods with the same name but different arguments. To work around this limitation, you can use a technique called method overloading using type switching. This involves using an interface to define multiple methods with the same name but different types, and then using a type switch to determine which method to call based on the type of the argument passed in. Here is an example:


type Stringer interface {
	String() string
}

type Person struct {
	Name string
	Age int
}

func (p *Person) String() string {
	return fmt.Sprintf("Person{Name: %s, Age: %d}", p.Name, p.Age)
}

func ToString(s Stringer) string {
	return s.String()
}

In this example, we have defined an interface named Stringer that contains a method named String. We have then implemented this interface on the Person type by creating a method named String that returns a string representation of the Person instance. Finally, we have created a function named ToString that takes a Stringer as an argument and returns the string representation of the instance.

Related Post -

Method Chaining in Go ->