From the course: Go Essentials: Concurrency, Connectivity, and High-Performance Apps

Unlock the full course today

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

Solution: Structs

Solution: Structs

(upbeat music) - [Instructor] Here is my solution. Initially we defined the square type to be struct with three fields, x, y, and length. Next we're going to define the new function. It gets parameters for each field. So x, y, and length and returns a pointer to a square and a possible error. First, we check for errors. In this case, if the length is smaller or equal to zero, we return an error. Then we create a square from the parameters and return a pointer to the square and nil signifying no error. Now the move method. So the move method gets delta x and delta y, and a pointer to a square as a pointer receiver, and adds delta x to x and delta y to y. The area, which does not change the square, can get a non pointer receiver to a square and return the length times length. And finally, we can combine all of these together. So we use the new function to create a square. If there is an error, we use the log.Fatalf…

Contents