2 回答
TA贡献2080条经验 获得超4个赞
package main
import (
"fmt"
"log"
"math/rand"
"time"
)
func main() {
// user score, no.of questions asked so far
var score, num int
var correct bool // temporary variable to decide if the answer is right
// questions
var questions = make([]string, 13)
t1 := time.Tick(time.Second * 7) // timer loop:
for {
select {
case <-t1:
log.Println("ran out of time")
break loop
default:
// have any questions further questions to ask
if num < len(questions) {
// simulate typing
time.Sleep(time.Millisecond * 777)
// correct or wrong answer
correct = (rand.Intn(777)%2 == 0)
if correct {
fmt.Println("you did it")
score++ //increase score
} else {
fmt.Println("try again")
}
} else {
// no questions, state and break
log.Println("all questions were finished")
break loop //break loop, all questions were finished
}
num++
}
}
//print final score
fmt.Println("your score is:", score)
}
TA贡献2065条经验 获得超13个赞
以非阻塞方式从通道读取的功能方式:
func CollectChanOne[T any](ch <-chan T) (T, bool) {
select {
case val, stillOpen := <-ch:
return val, stillOpen
default:
var zeroT T
return zeroT, false
}
}
示例: https: //go.dev/play/p/Njwyt32B4oT
注意此示例还有另一种方法 CollectChanRemaining() ,它读取通道中的所有缓冲元素。
- 2 回答
- 0 关注
- 85 浏览
添加回答
举报