gpt4 book ai didi

go - 在循环一个带有范围应用程序中断的 channel 之后

转载 作者:IT王子 更新时间:2023-10-29 02:25:12 25 4
gpt4 key购买 nike

我有一个问题,我的应用程序在 channel 循环后不会到达下一条语句。为了阐明我的意思,请查看以下代码片段。

func CreateAccount(name, email, password string) (string, string) {

validation := make(chan error)
errColl := make([]error, 3, 3)
iterator := 0

go func() {
nameErr := IsNameValid(name)
validation <- nameErr
}()

go func() {
emailErr := IsEmailValid(email)
validation <- emailErr

}()

go func() {
passwordErr := IsPasswordValid(password)
validation <- passwordErr
}()

for err := range validation {
errColl[iterator] = err
iterator++
}
fmt.Println("Hello")


return "hello", "dude"

}

这是我的创建帐户功能。在三个 goroutine 之后,我对 channel 验证进行了循环。循环完成后,语句

fmt.Println("Hello)

永远不会执行。但是当我像这样更改功能时。

func CreateAccount(name, email, password string) (string, string) {

validation := make(chan error)
errColl := make([]error, 3, 3)
//iterator := 0

go func() {
nameErr := IsNameValid(name)
validation <- nameErr
}()

go func() {
emailErr := IsEmailValid(email)
validation <- emailErr

}()

go func() {
passwordErr := IsPasswordValid(password)
validation <- passwordErr
}()

errColl[0] = <-validation
errColl[1] = <-validation
errColl[2] = <-validation
close(validation)
fmt.Println("Hello")

return "hello", "dude"

}

你好要打印出来,加上我得到了返回值。
我在第一个代码片段中做错了什么?

最佳答案

validation channel 永远不会关闭。

for err := range validation {
errColl[iterator] = err
iterator++
}

The Go Programming Language Specification

For statements

A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel.

For channels, the iteration values produced are the successive values sent on the channel until the channel is closed.

关于go - 在循环一个带有范围应用程序中断的 channel 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25222987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com