Go Method vs Function 🎯

beginner
6 min

Go Method vs Function 🎯

Welcome to your Go programming journey! Today, we're diving into one of the fundamental concepts - Go Methods and Functions. Let's get started! 🏃‍♂️

Understanding Functions 📝

A function is a set of instructions that performs a specific task. Go functions have the following characteristics:

  • Functions in Go are case sensitive
  • Functions can return one or more values
  • Functions can take zero or more arguments

Here's a simple function example:

go
func HelloWorld() { fmt.Println("Hello, World!") }

In this example, we've defined a function called HelloWorld that prints "Hello, World!" to the console when called.

Introducing Methods 💡

Methods in Go are functions associated with a struct or interface. They provide a way to operate on the struct's fields.

go
type Point struct { X int Y int } func (p *Point) Distance(p2 *Point) float64 { return math.Sqrt(float64(math.Pow(float64(p2.X-p.X), 2) + math.Pow(float64(p2.Y-p.Y), 2))) }

In this example, we've defined a Point struct and a method called Distance. The Distance method takes another Point as an argument and calculates the distance between the two points.

Note that the receiver p *Point is a pointer to the Point struct. This allows the method to modify the struct's fields if needed.

Method vs Function ✅

The main difference between methods and functions is that methods are associated with a specific data type (struct or interface), while functions are standalone entities.

Here's a quiz to test your understanding:

Quick Quiz
Question 1 of 1

Which of the following functions can operate on a `Point` struct?

Stay tuned for more Go lessons, where we'll explore more about methods, functions, and their practical applications! 🚀