Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Created July 12, 2011 21:34
Show Gist options
  • Save kylelemons/1079031 to your computer and use it in GitHub Desktop.
Save kylelemons/1079031 to your computer and use it in GitHub Desktop.
A (really naive) example of controlling variables via a goroutine
package main
import (
"fmt"
)
type Gender int
const (
Male Gender = iota
Female
Other
Unspecified
)
type Operation int
const (
Get Operation = iota
Set
)
type Command struct {
Op Operation
Var string
Value interface{}
Return chan interface{}
}
func run(in <-chan Command) {
var (
name string
age int
gender Gender
address []string
)
for o := range in {
switch o.Var {
case "name":
switch o.Op {
case Get:
o.Return <- name
case Set:
name = o.Value.(string)
o.Return <- true
default:
o.Return <- false
}
case "age":
switch o.Op {
case Get:
o.Return <- age
case Set:
age = o.Value.(int)
o.Return <- true
default:
o.Return <- false
}
case "gender":
switch o.Op {
case Get:
o.Return <- gender
case Set:
gender = o.Value.(Gender)
o.Return <- true
default:
o.Return <- false
}
case "address":
switch o.Op {
case Get:
o.Return <- address
case Set:
address = o.Value.([]string)
o.Return <- true
default:
o.Return <- false
}
default:
o.Return <- false
}
}
}
func main() {
cmd := make(chan Command)
go run(cmd)
sync := make(chan interface{})
cmd <- Command{
Op: Set,
Var: "name",
Value: "Gopher",
Return: sync,
}
<-sync
cmd <- Command{
Op: Get,
Var: "name",
Return: sync,
}
fmt.Printf("Name: %v\n", <-sync)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment