Skip to content

Instantly share code, notes, and snippets.

@savaki
Created April 30, 2015 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savaki/c085cc86bb9dfb74c700 to your computer and use it in GitHub Desktop.
Save savaki/c085cc86bb9dfb74c700 to your computer and use it in GitHub Desktop.
Re: A Rust Contributor Tries Their Hand at Go
package main
import "os"
var (
Red = rgb(255, 0, 0)
Blue = rgb(0, 0, 255)
)
func rgb(red, green, blue int) Color {
return Color(red<<16 + green<<8 + blue)
}
type Color int
type Point struct {
x int
y int
}
type Graphics interface {
// add your graphics thingies here
}
type Action func(Graphics)
func Quit(g Graphics) {
os.Exit(0)
}
func DrawLine(color Color, a Point, b Point) Action {
return func(g Graphics) {
// draw a line with the graphics context
}
}
func DrawTriangle(color Color, fill Color, a Point, b Point) Action {
return func(g Graphics) {
// draw a triangle with the graphics context
}
}
func SetBackground(color Color) Action {
return func(g Graphics) {
// set the background
}
}
func paintingLoop(ch chan Action) {
// create your graphics context here
var g Graphics = nil
// shorthand for a loop over receiving over
// a channel
for action := range ch {
action(g)
}
}
func drawThingy(ch chan Action) {
ch <- DrawLine(Red, Point{x: 0, y: 0}, Point{x: 1, y: 1})
ch <- SetBackground(Blue)
// Not possible
// ch <- true
// ch <- "foobar"
}
func main() {
// do some setup
ch := make(chan Action, 100)
// Creates a goroutine which will handle the
// event loop
go func() {
// create the window, etc
paintingLoop(ch)
}()
// ch can be handed out to various
// consumers now
drawThingy(ch)
}
@savaki
Copy link
Author

savaki commented Apr 30, 2015

Here's a rework of the original go program in (hopefully) a more idiomatic go style.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment