2
1
Fork 0

documentation for methods and interfaces

main
Sebastian Steger 2025-10-13 12:36:59 +02:00
parent 430baff10f
commit e985f4b4db
2 changed files with 10 additions and 2 deletions

View File

@ -6,12 +6,14 @@ type Counter struct {
value int 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() { func (c *Counter) Increment() {
c.value++ 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 { func (c Counter) String() string {
return fmt.Sprintf("Counter value: %d", c.value) return fmt.Sprintf("Counter value: %d", c.value)
} }

View File

@ -14,12 +14,14 @@ type rect struct {
width, height float64 width, height float64
} }
// Ensure that rect implements the geometry interface
var _ geometry = rect{} var _ geometry = rect{}
type circle struct { type circle struct {
radius float64 radius float64
} }
// Ensure that circle implements the geometry interface
var _ geometry = circle{} var _ geometry = circle{}
func (r rect) area() float64 { func (r rect) area() float64 {
@ -36,12 +38,16 @@ func (c circle) perim() float64 {
return 2 * math.Pi * c.radius return 2 * math.Pi * c.radius
} }
//Metods demonstrates how to use an interface
func measure(g geometry) { func measure(g geometry) {
fmt.Println(g) fmt.Println(g)
fmt.Println(g.area()) fmt.Println(g.area())
fmt.Println(g.perim()) fmt.Println(g.perim())
} }
//Method demonstrates casting an interface to a concrete type.
//Should be avoided in practice whenever possible.
func detectCircle(g geometry) { func detectCircle(g geometry) {
if c, ok := g.(circle); ok { if c, ok := g.(circle); ok {
fmt.Println("circle with radius", c.radius) fmt.Println("circle with radius", c.radius)