gpt4 book ai didi

go - golang 中 = 和 <- 有什么区别

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

func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "processing job", j)
time.Sleep(time.Second)
results <- j * 2
}
}

func main() {
t := time.Now()
fmt.Println(t)
jobs := make(chan int, 100)
results := make(chan int, 100)
for w := 1; w <= 4; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= 20; j++ {
jobs <- j
}
close(jobs)
for a := 1; a <= 20; a++ {
<-results
}

t = time.Now()
fmt.Println(t)
}

我对“<-”感到困惑,找不到任何关于“<-”的相关文档。那么 <- 和 = 有什么区别?为什么我不能在这里使用 =?

最佳答案

= operator像大多数语言一样处理变量赋值。它表达了想要更新标识符引用的值的想法。 <- operator表示将值从 channel 传递到引用的想法。如果您使用赋值运算符将 channel 视为队列 =会将对队列的引用分配给目标变量。接收运算符(operator) <-相当于从队列中出队,将item的值赋值给目标变量。

由于类型不匹配,您不能互换使用运算符。请注意 Go 规范的链接,这些链接对运算符(operator)进行了更详细的说明。

关于go - golang 中 = 和 <- 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33325395/

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