From the course: Treating Go as an Object-Oriented Language

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Solution: Struct as class

Solution: Struct as class

(upbeat music) - [Instructor] Now it's time for my solution to this challenge exercise. What I've done is down here in the GetArea method, I implemented it by doing a r.length times r.width which is the formula to calculate the area of a rectangle. And then I returned that. Notice that I'm referencing the attributes of the struct by its reference in the function definition. In the same way on GetPerimeter, I did two times the length plus two times the width, again, referencing the values from the struct, the attributes of the struct themselves, and then doing the appropriate math to get the perimeter of a rectangle. So now if I run my code, you will see that I get the results back that I would expect, which is that, in this case, the area is 32 and the perimeter is 24. And of course we can change the values so that width is 5 and, let's say, 10 for the length. And test that code again. And now you'll see that we get…

Contents