Advertisement
cwchen

[Go] Embedding a pointer.

Oct 5th, 2017
829
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.09 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "log"
  5. )
  6.  
  7. type Point struct {
  8.     x float64
  9.     y float64
  10. }
  11.  
  12. func NewPoint(x float64, y float64) *Point {
  13.     p := new(Point)
  14.  
  15.     p.SetX(x)
  16.     p.SetY(y)
  17.  
  18.     return p
  19. }
  20.  
  21. func (p *Point) X() float64 {
  22.     return p.x
  23. }
  24.  
  25. func (p *Point) Y() float64 {
  26.     return p.y
  27. }
  28.  
  29. func (p *Point) SetX(x float64) {
  30.     p.x = x
  31. }
  32.  
  33. func (p *Point) SetY(y float64) {
  34.     p.y = y
  35. }
  36.  
  37. type Point3D struct {
  38.     // Point is embedded as a pointer
  39.     *Point
  40.     z float64
  41. }
  42.  
  43. func NewPoint3D(x float64, y float64, z float64) *Point3D {
  44.     p := new(Point3D)
  45.  
  46.     // Forward promotion
  47.     p.Point = NewPoint(x, y)
  48.  
  49.     // Forward promotion
  50.     p.Point.SetX(x)
  51.     p.Point.SetY(y)
  52.  
  53.     p.SetZ(z)
  54.  
  55.     return p
  56. }
  57.  
  58. func (p *Point3D) Z() float64 {
  59.     return p.z
  60. }
  61.  
  62. func (p *Point3D) SetZ(z float64) {
  63.     p.z = z
  64. }
  65.  
  66. func main() {
  67.     p := NewPoint3D(1, 2, 3)
  68.  
  69.     // GetX method is from Point
  70.     if !(p.X() == 1) {
  71.         log.Fatal("Wrong value")
  72.     }
  73.  
  74.     // GetY method is from Point
  75.     if !(p.Y() == 2) {
  76.         log.Fatal("Wrong value")
  77.     }
  78.  
  79.     // GetZ method is from Point3D
  80.     if !(p.Z() == 3) {
  81.         log.Fatal("Wrong value")
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement