methodset2.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // methodset2.go
  2. package main
  3. import (
  4. "fmt"
  5. )
  6. type List []int
  7. func (l List) Len() int { return len(l) }
  8. func (l *List) Append(val int) { *l = append(*l, val) }
  9. type Appender interface {
  10. Append(int)
  11. }
  12. func CountInto(a Appender, start, end int) {
  13. for i := start; i <= end; i++ {
  14. a.Append(i)
  15. }
  16. }
  17. type Lener interface {
  18. Len() int
  19. }
  20. func LongEnough(l Lener) bool {
  21. return l.Len()*10 > 42
  22. }
  23. func main() {
  24. // A bare value
  25. var lst List
  26. // compiler error:
  27. // cannot use lst (type List) as type Appender in function argument:
  28. // List does not implement Appender (Append method requires pointer receiver)
  29. // CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver
  30. if LongEnough(lst) { // VALID: Identical receiver type
  31. fmt.Printf(" - lst is long enough")
  32. }
  33. // A pointer value
  34. plst := new(List)
  35. CountInto(plst, 1, 10) // VALID: Identical receiver type
  36. if LongEnough(plst) { // VALID: a *List can be dereferenced for the receiver
  37. fmt.Printf(" - plst is long enough") // - plst is long enoug
  38. }
  39. }