Skip to content

Commit

Permalink
Interface example embellished, use slice instead of array.
Browse files Browse the repository at this point in the history
  • Loading branch information
gmallard committed Jul 1, 2012
1 parent ebd4b21 commit ca54f0d
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
1 change: 1 addition & 0 deletions Makefile
Expand Up @@ -32,6 +32,7 @@ dirs = testppack \
interface_03 \
interface_04 \
interface_04a \
interface_04b \
list \
list_struct \
loghello \
Expand Down
92 changes: 92 additions & 0 deletions 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...")
}

0 comments on commit ca54f0d

Please sign in to comment.