Methods interfaces
Méthodes et interfaces en Go¶
Go n'est pas orienté objet (pas de notion de class ou d'hérirage). Par contre, on peut définir des méthodes sur des types existants.
In [ ]:
Copied!
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{3, 4}
fmt.Println(v.Abs())
}
package main
import (
"fmt"
"math"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func main() {
v := Vertex{3, 4}
fmt.Println(v.Abs())
}
5
On peut définir des méthodes sur uniquement sur des types locaux (définis dans le même package).
In [6]:
Copied!
package main
import (
"fmt"
"math"
)
type MyInt int
func (i MyInt) reverseSign() int {
return int(-i)
}
func main() {
i := MyInt(10)
fmt.Println(i.reverseSign())
}
package main
import (
"fmt"
"math"
)
type MyInt int
func (i MyInt) reverseSign() int {
return int(-i)
}
func main() {
i := MyInt(10)
fmt.Println(i.reverseSign())
}
-10