×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Function Method

Last Updated : July 21, 2025

In Go, methods are functions that are associated with a specific type. Unlike regular functions, methods have a receiver, which allows the function to operate on values of a particular type.

What is a Method in Go?

A method is a function with a special receiver argument. This receiver can either be a value type or a pointer type. Methods let you define behavior that belongs to a specific type.

Syntax

Here is the syntax to define a method:

// Syntax of method
func (receiver Type) methodName(params) returnType {
    // method body
}

Defining Methods on Structs

You can associate a method with a struct type. This is useful to define behaviors specific to the struct's data.

Example

This example shows how to define and call methods on a struct:

package main
import "fmt"

type Rectangle struct {
    width  float64
    height float64
}

// Method with value receiver
func (r Rectangle) area() float64 {
    return r.width * r.height
}

// Method with pointer receiver
func (r *Rectangle) scale(factor float64) {
    r.width *= factor
    r.height *= factor
}

func main() {
    rect := Rectangle{width: 4, height: 3}
    fmt.Println("Area before scaling:", rect.area())

    rect.scale(2)
    fmt.Println("Area after scaling:", rect.area())
}

When you run the above code, the output will be:

Area before scaling: 12
Area after scaling: 48

Method with Value vs Pointer Receiver

If a method uses a value receiver, it gets a copy of the receiver. Changes made inside the method do not affect the original value. A pointer receiver allows the method to modify the original value.

Example

Demonstrates how changes reflect only with pointer receivers:

package main
import "fmt"

type Counter struct {
    value int
}

// Method with value receiver (won’t modify original)
func (c Counter) incrementValue() {
    c.value++
}

// Method with pointer receiver (will modify original)
func (c *Counter) incrementPointer() {
    c.value++
}

func main() {
    c := Counter{value: 10}
    c.incrementValue()
    fmt.Println("After incrementValue:", c.value)

    c.incrementPointer()
    fmt.Println("After incrementPointer:", c.value)
}

When you run the above code, the output will be:

After incrementValue: 10
After incrementPointer: 11

Exercise

Test your understanding of methods in Go.

  1. What is a method in Go?
  2. What does a pointer receiver allow a method to do?
  3. Can both value and pointer receivers be used to define methods?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.