亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通道關閉時收到的布爾標志與 Golang 中的預期不同

通道關閉時收到的布爾標志與 Golang 中的預期不同

Go
qq_遁去的一_1 2022-06-13 16:06:45
我有一種用于重復身份驗證的類型:type Authorizer struct {    requester    *Requester    closeChannel chan error}func (requester *Requester) Authorize(autoClose bool) {    // Create a new authorizer from the requester and the close-channel    authorizer := Authorizer{        requester:    requester,        closeChannel: requester.closer,    }    // Ensure that the requester has a reference to the authorizer so we can access the    // updated token    requester.authorizer = &authorizer    // Begin the authentication loop concurrently    go authorizer.manageAuthorization()}func (authorizer *Authorizer) manageAuthorization() {    for {        select {        case _, ok := <-authorizer.closeChannel:            if ok {                fmt.Printf("Closed\n")                return // NEVER RUNS            }        default:            break        }        fmt.Printf("Not closed\n")        // Do inner authorization logic    }}此類創建身份驗證器并處理請求:type Requester struct {    authorizer   *Authorizer    client       *http.Client    closer       chan error}func NewRequester() *Requester {    requester := Requester{        client: new(http.Client),        closer: make(chan error),    }    requester.Authorize(false)    return &requester}func (requester *Requester) Close() {    fmt.Printf("Closing...\n")    close(requester.closer)}所以,到目前為止,我的測試都通過了這段代碼。但是,我在進行報道時遇到了一個有趣的問題。考慮以下代碼段:// Create the test clientclient := Requester{}client.closer = make(chan error)// Begin authenticationclient.Authorize(false)// Now, close the channelclose(client.closer)如果我將它嵌入到測試中并嘗試使用它運行代碼覆蓋率,我注意到指示的行永遠不會運行。此外,我在此處添加的調試消息顯示如下:Not closedNot closedNot closedClosing...Not closedNot closedNot closed消息不會Closed打印。那么,我在這里做錯了什么?
查看完整描述

1 回答

?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

ok將false在通道關閉時。嘗試


case _, ok := <-authorizer.closeChannel:

    if !ok {

        return // RUNS

    }


查看完整回答
反對 回復 2022-06-13
  • 1 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號