Search⌘ K
AI Features

Solution Review: Coordinates of a Point

Explore how to define and use structs and methods in Go by working with a 2D Point struct. Understand pointer receiver methods like Abs() and Scale(), and apply these techniques to manipulate point coordinates for practical programming challenges.

We'll cover the following...
Go (1.6.2)
package main
import (
"fmt"
"math"
)
type Point struct { /// struct of type Point
X, Y float64
}
func (p *Point)Abs() float64 { // method calculating absolute value
return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
}
func (p *Point)Scale(s float64) { // method to scale a point
p.X = p.X * s
p.Y = p.Y * s
return
}
func main() {
p1 := new(Point)
p1.X = 3
p1.Y = 4
fmt.Printf("The length of the vector p1 is: %f\n", p1.Abs() ) // calling Abs() func
p2:= &Point{4, 5}
fmt.Printf("The length of the vector p2 is: %f\n", p2.Abs() ) // calling Abs() func
p1.Scale(5) // calling Scale() fucn
fmt.Printf("The length of the vector p1 is: %f\n", p1.Abs() ) // calling Abs() func
fmt.Printf("Point p1 scaled by 5 has the following coordinates: X %f - Y %f", p1.X, p1.Y)
}

In the above code, look at line 7. We make a struct of type Point that is a 2D point. It has two fields X and Y, both of type float64.

Now, we need to write a method Abs(). See its header at line 11: func (p *Point)Abs() float64 . From its header, it’s clear that this method can be called only by a pointer to the object of type Point. In the next line, the ...