Logo

Developer learning path

Go

Methods on Structs in Go

Methods on Structs

42

#description

Sure! In Go, a struct is a composite type that groups together zero or more named values with different data types into a single entity. Structs are similar to classes in other object-oriented programming (OOP) languages such as Java, but Go does not have classes, so structs are used instead.

Methods in Go are functions that are associated with a type, and they can be defined on both named and anonymous types. In the case of structs, we can define methods on a struct type to give it new behaviors or to modify the values or properties of the struct directly.

Here's an example of defining a method on a struct in Go:

                    
type Rectangle struct {
    width  float64
    height float64
}

func (r Rectangle) area() float64 {
    return r.width * r.height
}
                  

In this example, we define a struct called Rectangle with two properties: width and height. We then define a method called area() which calculates and returns the area of the rectangle. The method uses the receiver notation "(r Rectangle)" to indicate that it is associated with the Rectangle struct.

To use the method, we can create an instance of the Rectangle struct and call the area() method on it:

                    
r := Rectangle{3, 4}
fmt.Println("Area of rectangle:", r.area()) // Output: Area of rectangle: 12
                  

This will output the area of the rectangle, which in this case is 12.

In summary, methods on structs allow us to extend the behavior of a struct and make it more flexible and reusable. By defining methods on a struct type, we can add new functionality and behaviors to our programs.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.