Неблокирующий канал в ходу - PullRequest
0 голосов
/ 01 октября 2018

У меня есть такой код:

go func(ch chan bool) chan bool {

    // some processing
    ch <- true
    return ch
}(ch)

for i := 0; i < TotalQuestions; i++ {
    // check if channel ch has some value
    // If it has then execute below statements, else break out of the loop


    fmt.Println(questions[i])
    answer, _ := InputReader.ReadString('\n')

    // some processing

}
fmt.Println("Your Total score is " + strconv.Itoa(TotalScore) + " out of " + strconv.Itoa(TotalQuestions))

Теперь я хочу проверить, имеет ли канал ch значение (цикл for).Если оно имеет значение, я хочу выйти из цикла for, чтобы напечатать последний оператор.в противном случае я хочу продолжить мой цикл.Я попытался вставить блок выбора, но это не сработало (канал заблокирован, а код не печатал вопросы).Как это сделать?

1 Ответ

0 голосов
/ 01 октября 2018
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)
}
...