Search⌘ K

Solution Review: Make a Rectangle

Understand how to define structs and attach methods in Go by reviewing a practical example of a Rectangle struct. Learn how to calculate area and perimeter, create instances, and call methods to handle struct data effectively.

We'll cover the following...
Go (1.6.2)
package main
import "fmt"
type Rectangle struct { // struct of type Rectangle
length, width int
}
func (r *Rectangle) Area() int { // method calculating area of rectangle
return r.length * r.width
}
func (r *Rectangle) Perimeter() int { // method calculating perimeter of rectangle
return 2* (r.length + r.width)
}
func main() {
r1 := Rectangle{4, 3}
fmt.Println("Rectangle is: ", r1)
fmt.Println("Rectangle area is: ", r1.Area()) // calling method of area
fmt.Println("Rectangle perimeter is: ", r1.Perimeter()) // calling method of perimeter
}

In the above code, at line 4, we make a struct Rectangle containing two fields length and width of type int. Then, we have two important methods Area() and Perimeter(). Look at the header of Area ...