diff --git a/Makefile b/Makefile index 52ed430..c027967 100644 --- a/Makefile +++ b/Makefile @@ -32,6 +32,7 @@ dirs = testppack \ interface_03 \ interface_04 \ interface_04a \ + interface_04b \ list \ list_struct \ loghello \ diff --git a/interface_04b/interface_04b.go b/interface_04b/interface_04b.go new file mode 100644 index 0000000..72e8e71 --- /dev/null +++ b/interface_04b/interface_04b.go @@ -0,0 +1,92 @@ +/* +A more realistic demonstration of interfaces, with explicit (?) declaration. +*/ +package main + +import ( + "fmt" // +) + +type Gap interface { + // Get data + Get() (s string, e error) + // Put data + Put(s string) (e error) +} + +// Will implement Gap +type ImpOne struct { + Gap // Implement Gap + ios string +} + +// Implement Gap.Get +func (o *ImpOne) Get() (s string, e error) { + return o.ios, nil +} + +// Implement Gap.Put +func (o *ImpOne) Put(s string) (e error) { + o.ios = s + return nil +} + +// Will also implement Gap +type ImpTwo struct { + Gap // Implement Gap + its string +} + +// Implement Gap.Get +func (o *ImpTwo) Get() (s string, e error) { + return o.its + o.its, nil +} + +// Implement Gap.Put +func (o *ImpTwo) Put(s string) (e error) { + o.its = s + s + return nil +} + +func main() { + fmt.Println("Start...") + + // ImpOne pointer + dOne := &ImpOne{} // Parmater initialization not allowed like this + fmt.Println("dOne.ios:", dOne.ios) + + // ImpTwo pointer + dTwo := &ImpTwo{} // Parmater initialization not allowed like this + fmt.Println("dTwo.its:", dTwo.its) + + // ImpOne leaves data alone + _ = dOne.Put("1time") + w, _ := dOne.Get() + fmt.Println("dOnePutGet", "1time", w) + + // ImpTwo munges the data + _ = dTwo.Put("1time") + w, _ = dTwo.Get() + fmt.Println("dTwoPutGet", "1time", w) + + // An slice of Gaps + ga := []Gap{dOne, dTwo} + + // Use array offsets + w, _ = ga[0].Get() + fmt.Println("ga0Get", w) + w, _ = ga[1].Get() + fmt.Println("ga1Get", w) + + // Declare a Gap and use offset 0 + var g Gap = ga[0] + w, _ = g.Get() + fmt.Println("gga0Get", w) + + // Now use offset 1 + g = ga[1] + w, _ = g.Get() + fmt.Println("gga1Get", w) + + fmt.Println("End...") +}