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

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

GO 頻道突然結束?

GO 頻道突然結束?

Go
慕婉清6462132 2022-11-08 16:06:57
我正在嘗試使用 go 通道同時生成帳戶(下面是簡化的代碼),但是我看到它并沒有生成所有帳戶:package mainimport (    "fmt"    "github.com/segmentio/ksuid")const ConcurrencyLevel = 10const TotalAccounts = 30type (    Accounts []Account     Account struct {        AccountID   string    })func GenerateRandomAccountID() (accountReferenceID string){    return ksuid.New().String()}func main() {    totalAccounts := make(Accounts, 0, TotalAccounts)    total := 0    for total < TotalAccounts {        accounts := make([]Account, ConcurrencyLevel)        ch := make(chan Account)        for range accounts {            go func() {                accountID := GenerateRandomAccountID()                account := Account{AccountID: accountID}                ch <- account            }()        }        for k, _ := range accounts {            account := <-ch            accounts[k] = account        }        totalAccounts = append(totalAccounts, accounts...)        total += len(totalAccounts)        close(ch)    }    fmt.Printf("total is : %d\n", total)    fmt.Printf("total accounts generated is : %d\n", len(totalAccounts))}它打印出來total is : 30total accounts generated is : 20在這種情況下,預計生成的帳戶總數為 30。https://go.dev/play/p/UtFhE2nidaP
查看完整描述

1 回答

?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

你的邏輯有錯誤:


totalAccounts = append(totalAccounts, accounts...)

total += len(totalAccounts)

假設這是循環的第二次迭代。totalAccounts已經包含 10 個項目,您再添加 10 個,因此長度現在為 20。然后您取total(從第一次運行開始將是 10)并添加len(totalAccounts)(20) 以得到 30 的結果。這意味著您的循環 ( for total < TotalAccounts) 完成早于應有的。


要解決此問題,您可以使用playground:


totalAccounts = append(totalAccounts, accounts...)

total += len(accounts) // Add the number of NEW accounts

或者


totalAccounts = append(totalAccounts, accounts...)

total = len(totalAccounts ) // = not +=


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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