From 8c1408dd8e224e146651deb1e9a16d5e789c15b3 Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Thu, 27 Mar 2008 21:42:25 -0700 Subject: [PATCH] Add select statement SVN=114147 --- doc/go_lang.txt | 62 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/doc/go_lang.txt b/doc/go_lang.txt index d30675e064..319de951f9 100644 --- a/doc/go_lang.txt +++ b/doc/go_lang.txt @@ -1163,7 +1163,7 @@ Statements control execution. [ LabelDecl ] ( StructuredStat | UnstructuredStat ) . StructuredStat = - Block | IfStat | SwitchStat | ForStat | RangeStat . + Block | IfStat | SwitchStat | SelectStat | ForStat | RangeStat . UnstructuredStat = Declaration | SimpleVarDecl | @@ -1399,6 +1399,65 @@ If the expression is omitted, it is equivalent to "true". } +Select statements +---- + +A select statement chooses which of a set of possible communications +will proceed. It looks similar to a switch statement but with the +cases all referring to communication operations. + + SelectStat = "select" "{" { CommClause } "}" . + CommClause = CommCase { Statement } . + CommCase = ( "default" | ( "case" ( SendCase | RecvCase) ) ) ":" . + SendCase = Send . + RecvCase = [ identifier '=' ] RecvExpression . + RecvExpression = '<' Expression . + +The select statement evaluates all the channel (pointers) involved. +If any of the channels can proceed, the corresponding communication +and statements are evaluated. Otherwise, if there is a default case, +that executes; if not, the statement blocks until one of the +communications can complete. A channel pointer may be nil, which is +equivalent to that case not being present in the select statement. + +If the channel sends or receives "any" or an interface type, its +communication can proceed only if the type of the communication +clause matches that of the dynamic value to be exchanged. + +If multiple cases can proceed, a uniform fair choice is made regarding +which single communication will execute. + + var c, c1, c2 *chan int; + select { + case i1 = c2 = i2: + printf("sent %d to c2\n", i2); + default: + printf("no communication\n"); + } + + for { // send random sequence of bits to c + select { + case >c = 0: // note: no statement, no fallthrough, no folding of cases + case >c = 1: + } + } + + var ca *chan any; + var i int; + var f float; + select { + case i =