Go Methods Introduction šŸŽÆ

beginner
16 min

Go Methods Introduction šŸŽÆ

Welcome to our deep dive into Go Methods! In this lesson, we'll explore how to create, use, and understand methods - functions associated with a data type in the Go programming language. Let's get started!

What are Methods? šŸ“

Methods are functions that are defined within a data type (struct or interface) and operate on the data that the data type holds. Methods can access and manipulate the data directly, making them a powerful tool in your Go toolkit.

Creating Methods šŸ’”

To create a method, we'll define it within a data type and use the func keyword. Here's an example with a simple Point struct that has methods for calculating the distance and area.

go
type Point struct { x, y float64 } func (p Point) Distance(other Point) float64 { return math.Sqrt((other.x-p.x)*(other.x-p.x) + (other.y-p.y)*(other.y-p.y)) } func (p Point) Area() float64 { return p.x * p.y / 2 }

In the example above, we have created two methods for the Point struct:

  1. Distance(other Point) float64 - calculates the distance between two points.
  2. Area() float64 - calculates the area of a rectangle with the given point as one corner and the x and y coordinates as width and height.

šŸ’” Pro Tip: The p used inside the parentheses is called a receiver, and it represents the data type the method is associated with. The receiver can be the method's first parameter, and it allows the method to access the struct fields directly.

Using Methods āœ…

Now that we have our methods, let's see how to use them.

go
func main() { p1 := Point{1, 2} p2 := Point{3, 4} fmt.Println("Distance:", p1.Distance(p2)) fmt.Println("Area:", p1.Area()) }

In the example above, we create two points and call the methods on them.

Methods and Types šŸ“

Methods are strongly typed, meaning they can only be called on data types they are defined for. Go automatically infers the data type of a method receiver, but you can also specify the data type explicitly using a dot (.) if needed.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What is a method in Go?

Quick Quiz
Question 1 of 1

How do we call a method in Go?

That's it for our introduction to Go Methods! In the next lesson, we'll dive deeper into method best practices and explore more advanced techniques. Happy coding! šŸš€