禁用选择语句的默认部分

我想要一种在选择语句的默认部分进行处理的方法,然后稍后禁用默认值。


我在下面的代码中使用了 if 语句,但是,在完成后,我们只有一个繁忙的循环(当通道为空时)将继续旋转测试完成的标志,这将始终为真。这似乎不是正确的方法。


for {

    select {

    case p := <-subscriber.Next:

        ...

    case err := <subsriber.OnError:

        ...

    default:

        if !finished {

            subscriber.Subscribe(name, params)

            ...

            if ... { finished = true }

        }

        

    }

}

我知道你不能禁用默认部分,但必须有更好的方法来做到这一点。


一只名叫tom的猫
浏览 110回答 2
2回答

qq_遁去的一_1

您不能禁用default子句,但可以case通过分配nil给 chan 来禁用子句。也许像下面的代码一样创建一个非常快速的代码。下面的代码将 chanC从股票代码分配给defaultCh然后通过分配禁用它nil。&nbsp; &nbsp; ticker := time.NewTicker(time.Microsecond)&nbsp; &nbsp; defaultCh := ticker.C&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case p := <-subscriber.Next:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case err := <subscriber.OnError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case <-defaultCh:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; subscriber.Subscribe(name, params)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if finished {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defaultCh = nil&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ticker.Stop()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

MMTTMM

我不知道有任何内置功能可以执行此操作,但您可以根据您的状态输入两个不同的选择语句。for {&nbsp; &nbsp; // Without default case, wait only for cases&nbsp; &nbsp; if finished {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case p := <-subscriber.Next:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; &nbsp; &nbsp; case err := <-subsriber.OnError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // Allow default case&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case p := <-subscriber.Next:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; &nbsp; &nbsp; case err := <-subsriber.OnError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; subscriber.Subscribe(name, params)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}这当然会导致代码重复,但至少它不会进入循环只是发现什么都不需要做。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go