You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.8 KiB
75 lines
1.8 KiB
/*
|
|
Landesamt für Geoinformation und Landentwicklung, Referat 35
|
|
Einführung in die Sprache Go, 25.7.2017
|
|
Lektion 8: Exkurs zur Objektorientierung
|
|
*/
|
|
package main
|
|
|
|
import "fmt"
|
|
import "math"
|
|
|
|
//Schlechter Stil bei der Reihenfolge, dient hier der Anschaulichkeit (Besser: type interface - type struct - func)
|
|
type StructA struct {
|
|
FieldA1, FieldA2 float64
|
|
}
|
|
|
|
func (thisA StructA) FMethod1() float64 {
|
|
return thisA.FieldA1 * thisA.FieldA2
|
|
}
|
|
func (thisA StructA) FMethod2() float64 {
|
|
return thisA.FieldA1 + thisA.FieldA2
|
|
}
|
|
|
|
type StructB struct {
|
|
FieldB1 float64
|
|
}
|
|
|
|
func (thisB StructB) FMethod1() float64 {
|
|
return math.Pow(thisB.FieldB1, 2)
|
|
}
|
|
func (thisB StructB) FMethod2() float64 {
|
|
return math.Sqrt(thisB.FieldB1)
|
|
}
|
|
|
|
type IFace interface {
|
|
FMethod1() float64
|
|
FMethod2() float64
|
|
}
|
|
|
|
func FPolyfunc(i IFace) {
|
|
fmt.Println(i, i.FMethod1(), i.FMethod2())
|
|
}
|
|
|
|
func FPolyfuncR(i IFace) IFace {
|
|
return (i)
|
|
}
|
|
|
|
func main() {
|
|
//1a. Implementierung der Methoden über die Struktur, …
|
|
var a StructA
|
|
var b StructB
|
|
a = StructA{FieldA1: 10, FieldA2: 11} // a: = StructA{FieldA1: 10, FieldA2: 11}
|
|
b = StructB{FieldB1: 16} // b: = StructB{FieldB1: 16}
|
|
|
|
//fmt.Println(a) //{10 11}
|
|
//fmt.Println(b) //{12}
|
|
|
|
//1b. … Implementierung des Interfaces im Funktionskopf
|
|
FPolyfunc(a) //{10 11} 110 21
|
|
FPolyfunc(b) //{16} 256 4
|
|
|
|
//2. Implementierung der Methoden über das Interface (= identisches Resultat!)
|
|
var c, d IFace = StructA{FieldA1: 10, FieldA2: 11}, StructB{FieldB1: 16}
|
|
|
|
FPolyfunc(c) //{10 11} 110 21
|
|
FPolyfunc(d) //{16} 256 4
|
|
|
|
//3. Neuere Implementierungen überschreiben vorherige
|
|
var e IFace
|
|
|
|
e = StructA{FieldA1: 10, FieldA2: 11}
|
|
fmt.Println(e, e.FMethod1(), e.FMethod2()) //{10 11} 110 21
|
|
|
|
e = StructB{FieldB1: 16}
|
|
fmt.Println(FPolyfuncR(e), FPolyfuncR(e).FMethod1(), FPolyfuncR(e).FMethod2()) // {16} 256 4
|
|
}
|
|
|