Structs

Python

  1. from __future__ import division
  2. from math import sqrt
  3.  
  4.  
  5. class Point(object):
  6. def __init__(self, x, y):
  7. self.x = x
  8. self.y = y
  9.  
  10.  
  11. def distance(point1, point2):
  12. return sqrt(point1.x * point2.x + point1.y * point2.y)
  13.  
  14.  
  15. p1 = Point(1, 3)
  16. p2 = Point(2, 4)
  17. print distance(p1, p2) # 3.74165738677

Go

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "math"
  6. )
  7.  
  8. type Point struct {
  9. x float64
  10. y float64
  11. }
  12.  
  13. func distance(point1 Point, point2 Point) float64 {
  14. return math.Sqrt(point1.x*point2.x + point1.y*point2.y)
  15. }
  16.  
  17. // Since structs get automatically copied,
  18. // it's better to pass it as pointer.
  19. func distance_better(point1 *Point, point2 *Point) float64 {
  20. return math.Sqrt(point1.x*point2.x + point1.y*point2.y)
  21. }
  22.  
  23. func main() {
  24. p1 := Point{1, 3}
  25. p2 := Point{2, 4}
  26. fmt.Println(distance(p1, p2)) // 3.7416573867739413
  27. fmt.Println(distance_better(&p1, &p2)) // 3.7416573867739413
  28. }