Go Methods

What is a Method?

A method is a function that is attached to a specific type.

In Go, methods are commonly used with structs to define behavior.

Loading...
Output:

Calling a Method

Methods are called using the dot (.) operator on a variable.

This works similarly to calling methods on objects in other languages.

Loading...
Output:

Methods vs Functions

A regular function is not attached to any type, while a method belongs to a specific type.

Methods allow you to group behavior with data.

Loading...
Output:

Value Receivers

A value receiver creates a copy of the struct when the method is called.

Changes inside the method do not affect the original value.

Loading...
Output:

Pointer Receivers

A pointer receiver allows the method to modify the original struct.

This is commonly used when you want to update values.

Loading...
Output:

When to Use Pointer Receivers

Pointer receivers are preferred in most real-world cases.

  • When modifying the struct
  • When working with large structs (better performance)
  • To avoid unnecessary copying

Multiple Methods on a Struct

A struct can have multiple methods, allowing it to have different behaviors.

Loading...
Output:

Real-World Example

Methods are commonly used to model behavior in applications.

Loading...
Output:

Common Mistakes

Be careful with these:

  • Using value receiver when you need to modify data
  • Forgetting to use pointer (*) when needed
  • Confusing methods with regular functions

Practice

Create a Car struct with a method that prints its brand.

Loading...
Output:

Need Help?