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 - Go Tutorial
From the course: Treating Go as an Object-Oriented Language
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
-
-
-
-
(Locked)
Structs as classes2m 21s
-
(Locked)
Creating a struct5m 16s
-
(Locked)
Encapsulation2m 43s
-
(Locked)
Leveraging encapsulation5m 35s
-
(Locked)
Solution: Struct as class2m 2s
-
(Locked)
Composition1m 36s
-
(Locked)
Leveraging composition4m 11s
-
(Locked)
Polymorphism2m 59s
-
(Locked)
Leveraging polymorphism4m 49s
-
(Locked)
Solution: OOP4m 56s
-
(Locked)
-