How to calculate the distance between two points in 2D or 3D space in Go?

To calculate the distance between two points in 2D or 3D space in Go, you can use the following steps:

  1. Define struct types to represent the points. For example, you can define a Point2D struct for 2D space and a Point3D struct for 3D space. These structs should have fields to store the coordinates of the points.
type Point2D struct { X float64 Y float64 } type Point3D struct { X float64 Y float64 Z float64 }
  1. Define a function that calculates the distance between two points using the distance formula. The distance formula for 2D space is sqrt((x2-x1)^2 + (y2-y1)^2), and for 3D space, it is sqrt((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2).
import "math" func Distance2D(p1, p2 Point2D) float64 { return math.Sqrt(math.Pow(p2.X-p1.X, 2) + math.Pow(p2.Y-p1.Y, 2)) } func Distance3D(p1, p2 Point3D) float64 { return math.Sqrt(math.Pow(p2.X-p1.X, 2) + math.Pow(p2.Y-p1.Y, 2) + math.Pow(p2.Z-p1.Z, 2)) }

Note that in this example, we use the math package's Sqrt and Pow functions to calculate the square root and power, respectively.

  1. Instantiate two points with the desired coordinates and call the distance function to calculate the distance.
func main() { // 2D example p1 := Point2D{X: 3, Y: 4} p2 := Point2D{X: 6, Y: 8} distance2D := Distance2D(p1, p2) fmt.Println("Distance in 2D space:", distance2D) // 3D example p3 := Point3D{X: 1, Y: 2, Z: 3} p4 := Point3D{X: 4, Y: 5, Z: 6} distance3D := Distance3D(p3, p4) fmt.Println("Distance in 3D space:", distance3D) }

Make sure to import the necessary packages (fmt and math) and run the code to see the calculated distances in the output.