0
0
GoHow-ToBeginner · 3 min read

How to Create Method on Struct in Go: Simple Guide

In Go, you create a method on a struct by defining a function with a receiver argument of the struct type using func (s StructName) MethodName(). This receiver links the method to the struct, allowing you to call it on struct instances.
📐

Syntax

To create a method on a struct, use the syntax:

  • func (receiver StructType) MethodName() { }
  • receiver: a variable name representing the struct instance inside the method
  • StructType: the name of the struct the method belongs to
  • MethodName: the name of the method you want to create

This connects the method to the struct so you can call it like instance.MethodName().

go
func (s StructName) MethodName() {
    // method body
}
💻

Example

This example shows a struct Person with a method Greet that prints a greeting using the person's name.

go
package main

import "fmt"

type Person struct {
    Name string
}

func (p Person) Greet() {
    fmt.Printf("Hello, my name is %s.\n", p.Name)
}

func main() {
    person := Person{Name: "Alice"}
    person.Greet()
}
Output
Hello, my name is Alice.
⚠️

Common Pitfalls

1. Forgetting the receiver: Methods must have a receiver to be linked to a struct. Without it, the function is not a method.

2. Using pointer vs value receiver: Using a value receiver (func (p Person)) means the method works on a copy, so changes inside the method don't affect the original struct. Use a pointer receiver (func (p *Person)) to modify the original.

3. Receiver name conflicts: Use short, clear receiver names (like p for Person) to avoid confusion.

go
package main

import "fmt"

type Counter struct {
    Count int
}

// Wrong: value receiver, changes won't persist
func (c Counter) Increment() {
    c.Count++
}

// Correct: pointer receiver, changes persist
func (c *Counter) Increment() {
    c.Count++
}

func main() {
    c := Counter{Count: 0}
    c.Increment()
    fmt.Println(c.Count) // Output will be 0 if wrong, 1 if correct
}
Output
1
📊

Quick Reference

  • Define a method with func (receiver StructType) MethodName().
  • Use pointer receiver *StructType to modify struct fields inside methods.
  • Call methods on struct instances like instance.MethodName().
  • Receiver name is a local variable inside the method.

Key Takeaways

Create methods by defining functions with a receiver of the struct type.
Use pointer receivers to modify the original struct inside methods.
Call methods on struct instances using dot notation.
Receiver names should be short and meaningful for clarity.
Without a receiver, functions are not methods on structs.