// ========================================================================== // $Id: colinterface.go,v 1.1 2014/03/31 21:34:24 jlang Exp $ // CSI2120 GO: Interfaces // ========================================================================== // (C)opyright: // // Jochen Lang // EECS, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.eecs.uottawa.ca // // Creator: Jochen Lang (based on example by R. Laganiere) // Email: jlang@eecs.uottawa.ca // ========================================================================== // $Log: colinterface.go,v $ // Revision 1.1 2014/03/31 21:34:24 jlang // "Added examples for file I/O, methods, interfaces" // // ========================================================================== package main import ( "fmt" ) func main() { table := [...]Color{ &ColorPt{Point{1.1,2.2},"red"}, &Box{32.4, "yellow"}, &ColorPt{Point{3.1,1.2},"blue"}} for _,element := range table { fmt.Printf("color= %s\n", element.Color()) } } type Point struct { x float64 y float64 } type ColorPt struct { pt Point color string } type Box struct { weight float64 color string } // interface implemented by ColorPt and Box type Color interface { SetColor(string) Color() string } // Interface implementation for type ColorPt func (p *ColorPt) Color() string { return p.color } func (p *ColorPt) SetColor(col string) { p.color = col } // Interface implementation for type Box func (p *Box) SetColor(col string) { p.color = col } func (p *Box) Color() string { return p.color }