gpt4 book ai didi

go - 当我不使用 go 关键字时,函数不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:20 25 4
gpt4 key购买 nike

在这个函数中你可以看到我使用了go关键字。

package main

import (
"fmt"
"math"
)

func main() {
c := make(chan string)
go findGreatestDivisor(4, c)
for i := 0; i <= 1; i++ {
fmt.Println(<-c)
}
}

func findGreatestDivisor(num float64, c chan string) {
var counter float64 = 10000
for i := 9999; i > 0; i-- {
if math.Mod(num, counter) == 0 {
fmt.Println("Check..", math.Mod(4, 1))
c <- fmt.Sprintf("%f is divisble by %d", num, i)
}
counter--
}

}

它有效。它给了我最大的整数。但是现在我很好奇并删除了我在这里调用函数的 go 关键字

go findGreatestDivisor(4,c)

当我做的时候

findGreatestDivisor(4,c)

它给了我错误

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]: main.findGreatestDivisor(0x4010000000000000,
0xc82001a0c0)
/home/ubuntu/workspace/test.go:21 +0x37c main.main()
/home/ubuntu/workspace/test.go:10 +0x61 exit status 2

这是为什么?

最佳答案

The Go Programming Language Specification

Send statements

A send statement sends a value on a channel. The channel expression must be of channel type, the channel direction must permit send operations, and the type of the value to be sent must be assignable to the channel's element type.

SendStmt = Channel "<-" Expression .
Channel = Expression .

Both the channel and the value expression are evaluated before communication begins. Communication blocks until the send can proceed. A send on an unbuffered channel can proceed if a receiver is ready. A send on a buffered channel can proceed if there is room in the buffer. A send on a closed channel proceeds by causing a run-time panic. A send on a nil channel blocks forever.

ch <- 3  // send value 3 to channel ch

findGreatestDivisor

c := make(chan string)
findGreatestDivisor(4,c)

你尝试在无缓冲 channel c上发送

c <- fmt.Sprintf("%f is divisble by %d", num, i)

但通信阻塞,直到发送可以继续。如果接收方准备就绪,则可以继续进行无缓冲 channel 上的发送。没有接收器准备好。

channel c 上的接收

fmt.Println(<-c)

在您从 findGreatestDivisor 返回之前不会准备好。太晚了。

关于go - 当我不使用 go 关键字时,函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109239/

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