Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang 2 autochannels

For example there is a function

func add(a, b int) (x int) {
    // some work
    return
}

there is a wrapper

func asyncAdd(a, b int)  <-chan int {
  var ci = make(chan int, 1) // must be buffered
  go func(){
    defer close(ci) // to close or not to close, that is another question
    ci <- add(a, b)
  }()
  return ci
}

and there is a select statement

select {
case x :=<- asyncAdd(5, 6):
   // stuff
case x :=<- asyncAdd(90, 210):
   // stuff
}

why don't just

select {
case x :=<- go add():
    // stuff
case x :=<- go add():
    // stuff
}

and for exmaple if a fucntions has many replies

func some(a, b int, c string) (val string, err error) {
    // stuff
}

select {
case val, err :=<- go some(5,12, "hey"):
   // stuff
case val, err :=<- go some(65, 535, "port"):
   // stuff
}

what about?

E.g. every <- go can be treated as autocahannel statement.

@logrusorgru

This comment has been minimized.

Show comment
Hide comment
@logrusorgru

logrusorgru Sep 16, 2018

No values. And ignore values.

func some(a, b int) { /* stuff */ }

func anotherOne(a, b int) (user *User) { /* stuff */ }

select {
case <- go some(1, 2):
  // some(1, 2) finished first!
case <- go some(3, 4):
 // some(3, 4) finished first!
case <- go anotherOne(9, 10):
   // ignore value
}
Owner

logrusorgru commented Sep 16, 2018

No values. And ignore values.

func some(a, b int) { /* stuff */ }

func anotherOne(a, b int) (user *User) { /* stuff */ }

select {
case <- go some(1, 2):
  // some(1, 2) finished first!
case <- go some(3, 4):
 // some(3, 4) finished first!
case <- go anotherOne(9, 10):
   // ignore value
}
@logrusorgru

This comment has been minimized.

Show comment
Hide comment
@logrusorgru
Owner

logrusorgru commented Sep 17, 2018

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