Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 18th, 2012  |  syntax: None  |  size: 0.52 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package main
  2.  
  3. import (
  4.         "fmt"
  5.         "time"
  6. )
  7.  
  8. type Future struct {
  9.         feed chan interface{}
  10.         val interface{}
  11. }
  12.  
  13. func NewFuture() *Future {
  14.         return &Future{feed: make(chan interface{}, 1)}
  15. }
  16.  
  17. func (f *Future) Set(v interface{}) {
  18.         f.feed <- v
  19.         close(f.feed)
  20. }
  21.  
  22. func (f *Future) Get() interface{} {
  23.         v, ok := <-f.feed
  24.         if ok {
  25.                 f.val = v
  26.         }
  27.         return f.val
  28. }
  29.  
  30. func main() {
  31.         f := NewFuture()
  32.         go (func() {
  33.                 time.Sleep(1e9)
  34.                 f.Set(12)
  35.         })()
  36.         v := f.Get()
  37.         fmt.Println(v)
  38.         v = f.Get()
  39.         fmt.Println(v)
  40. }