英文:
cap() on channel is not constant?
问题
ch := make(chan int, 10)
fmt.Println(cap(ch))
函数调用cap(ch)
是常量还是被计算的?
Golang规范中提到:
如果s是一个字符串常量,表达式len(s)是常量。如果s的类型是数组或指向数组的指针,并且表达式s不包含通道接收或(非常量)函数调用,则表达式len(s)和cap(s)是常量;在这种情况下,s不会被计算。否则,len和cap的调用不是常量,s会被计算。
看起来是被计算的。
英文:
ch := make(chan int, 10)
fmt.Println(cap(ch))
is function call cap(ch)
constant or evaluated?
golang spec said:
> The expression len(s) is constant if s is a string constant. The expressions len(s) and cap(s) are constants if the type of s is an array or pointer to an array and the expression s does not contain channel receives or (non-constant) function calls; in this case s is not evaluated. Otherwise, invocations of len and cap are not constant and s is evaluated.
seems that is evaluated.
答案1
得分: 6
是的,当应用于通道时,cap()
不是常量,因为通道的容量没有编码在类型中,因此在编译时是未知的。
英文:
Yes, cap()
is not constant when applied to a channel, as the capacity of a channel isn't encoded in the type and thus not known at compile time.
答案2
得分: 2
当执行cap(ch)
时,会返回通道ch
的容量。在给ch
分配10个整数的缓冲区后,cap(ch)
将返回10。然后,当将ch
重新分配为9个整数的缓冲区后,cap(ch)
将返回9。
这是一个示例代码的链接:https://play.golang.org/p/R0TfCpC-4L
英文:
Sure call cap(ch) evaluated, just because of
ch := make(chan int, 10)
fmt.Println(cap(ch))
ch = make(chan int, 9)
fmt.Println(cap(ch))
Proof-link https://play.golang.org/p/R0TfCpC-4L
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论