通道上的cap()不是常量吗?

huangapple go评论86阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年4月19日 23:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/29732049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定