Source file tour/methods/interfaces.go

     1  // +build no-build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  	"math"
     8  )
     9  
    10  type Abser interface {
    11  	Abs() float64
    12  }
    13  
    14  func main() {
    15  	var a Abser
    16  	f := MyFloat(-math.Sqrt2)
    17  	v := Vertex{3, 4}
    18  
    19  	a = f  // a MyFloat implements Abser
    20  	a = &v // a *Vertex implements Abser
    21  
    22  	// In the following line, v is a Vertex (not *Vertex)
    23  	// and does NOT implement Abser.
    24  	a = v
    25  
    26  	fmt.Println(a.Abs())
    27  }
    28  
    29  type MyFloat float64
    30  
    31  func (f MyFloat) Abs() float64 {
    32  	if f < 0 {
    33  		return float64(-f)
    34  	}
    35  	return float64(f)
    36  }
    37  
    38  type Vertex struct {
    39  	X, Y float64
    40  }
    41  
    42  func (v *Vertex) Abs() float64 {
    43  	return math.Sqrt(v.X*v.X + v.Y*v.Y)
    44  }
    45  

View as plain text