forked from steger/pr3-ws202526
documentation for methods and interfaces
parent
d443e58330
commit
a74265e4dc
|
|
@ -6,12 +6,14 @@ type Counter struct {
|
|||
value int
|
||||
}
|
||||
|
||||
// pointer receiver
|
||||
// pointer receiver. The method operates directly on the object c points to
|
||||
// Use a pointer receiver whenever the object needs to be modified.
|
||||
func (c *Counter) Increment() {
|
||||
c.value++
|
||||
}
|
||||
|
||||
// value receiver
|
||||
// value receiver. The method operates on copy of object c. Use a value
|
||||
// receiver when the object does not need to be modified in the method.
|
||||
func (c Counter) String() string {
|
||||
return fmt.Sprintf("Counter value: %d", c.value)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,12 +14,14 @@ type rect struct {
|
|||
width, height float64
|
||||
}
|
||||
|
||||
// Ensure that rect implements the geometry interface
|
||||
var _ geometry = rect{}
|
||||
|
||||
type circle struct {
|
||||
radius float64
|
||||
}
|
||||
|
||||
// Ensure that circle implements the geometry interface
|
||||
var _ geometry = circle{}
|
||||
|
||||
func (r rect) area() float64 {
|
||||
|
|
@ -36,12 +38,16 @@ func (c circle) perim() float64 {
|
|||
return 2 * math.Pi * c.radius
|
||||
}
|
||||
|
||||
//Metods demonstrates how to use an interface
|
||||
func measure(g geometry) {
|
||||
fmt.Println(g)
|
||||
fmt.Println(g.area())
|
||||
fmt.Println(g.perim())
|
||||
}
|
||||
|
||||
|
||||
//Method demonstrates casting an interface to a concrete type.
|
||||
//Should be avoided in practice whenever possible.
|
||||
func detectCircle(g geometry) {
|
||||
if c, ok := g.(circle); ok {
|
||||
fmt.Println("circle with radius", c.radius)
|
||||
|
|
|
|||
Loading…
Reference in New Issue