Skip to content

Instantly share code, notes, and snippets.

@up1
Last active August 29, 2015 14:01
Show Gist options
  • Save up1/fa1f0b620ef081c6a868 to your computer and use it in GitHub Desktop.
Save up1/fa1f0b620ef081c6a868 to your computer and use it in GitHub Desktop.
Demo=> Interface in Go
package main
import (
"fmt"
"net/http"
)
type Counter struct {
n int
}
func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctr.n++
fmt.Fprintf(w, "counter = %d\n", ctr.n)
}
func main() {
ctr := new(Counter)
http.Handle("/counter", ctr)
http.ListenAndServe("localhost:8888", nil)
}
package main
import "fmt"
type Shaper interface {
Area() float64
}
type Rectangle struct {
width float64
height float64
}
func (rectangle Rectangle) Area() float64 {
return rectangle.width * rectangle.height
}
type Square struct {
width float64
}
func (square Square) Area() float64 {
return square.width * square.width
}
type Circle struct {
redius float64
}
func (circle Circle) Area() float64 {
return circle.redius * circle.redius * 3.1415
}
func ComputeArea(shape Shaper) {
fmt.Printf("Area of %+v=%.3f\n", shape, shape.Area())
}
func main() {
rectangle := Rectangle{5, 10}
square := Square{5}
circle := Circle{5}
shapes := [...]Shaper{rectangle, square, circle}
for _, shape := range shapes {
ComputeArea(shape)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment