• API
• FAQ
• Tools
• Archive
SHARE
TWEET

[Go] IPoint interface demo. cwchen   Oct 7th, 2017 597 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. package main
2.
3. import (
4.     "fmt"
5. )
6.
7. type IPoint interface {
8.     X() float64
9.     Y() float64
10.     SetX(float64)
11.     SetY(float64)
12. }
13.
14. type Point struct {
15.     x float64
16.     y float64
17. }
18.
19. func NewPoint(x float64, y float64) *Point {
20.     p := new(Point)
21.
22.     p.SetX(x)
23.     p.SetY(y)
24.
25.     return p
26. }
27.
28. func (p *Point) X() float64 {
29.     return p.x
30. }
31.
32. func (p *Point) Y() float64 {
33.     return p.y
34. }
35.
36. func (p *Point) SetX(x float64) {
37.     p.x = x
38. }
39.
40. func (p *Point) SetY(y float64) {
41.     p.y = y
42. }
43.
44. type Point3D struct {
45.     // Point is embedded
46.     Point
47.     z float64
48. }
49.
50. func NewPoint3D(x float64, y float64, z float64) *Point3D {
51.     p := new(Point3D)
52.
53.     p.SetX(x)
54.     p.SetY(y)
55.     p.SetZ(z)
56.
57.     return p
58. }
59.
60. func (p *Point3D) Z() float64 {
61.     return p.z
62. }
63.
64. func (p *Point3D) SetZ(z float64) {
65.     p.z = z
66. }
67.
68. func main() {
69.     // Make a slice of IPoint
70.     points := make([]IPoint, 0)
71.
72.     p1 := NewPoint(3, 4)
73.     p2 := NewPoint3D(1, 2, 3)
74.     // No error!
75.     points = append(points, p1, p2)
76.
77.     for _, p := range points {
78.         fmt.Println(fmt.Sprintf("(%.2f %.2f)", p.GetX(), p.GetY()))
79.     }
80. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!

Top