dongyong5255
2019-03-21 20:32
浏览 138
已采纳

为什么在go常量中不允许使用“ math.Sin”?

According to Effective Go, the function math.Sin cannot be used to define a constant because that function must happen at run-time.

What is the reasoning behind this limitation? Floating-point consistency? Quirk of the Sin implementation? Something else?


There is support for this sort of thing in other languages. In C, for example: as of version 4.3, GCC supports compile-time calculation of the sine function. (See section "General Optimizer Improvements").

However, as noted in this blog post by Bruce Dawson, this can cause unexpected issues. (See section "Compile-time versus run-time sin").

Is this a relevant concern in Go? Or is this usage restricted for a different reason?

图片转代码服务由CSDN问答提供 功能建议

根据有效的Go ,函数 math.Sin 不能用于定义常量,因为该函数必须在运行时发生。

此限制背后的原因是什么? 浮点一致性? Sin 实现的怪癖? 还有其他东西吗?


其他语言也支持这种事情。 例如,在C语言中:从4.3版开始, GCC支持正弦的编译时计算 功能。 (请参见“常规优化工具的改进”部分。)

但是,如布鲁斯·道森(Bruce Dawson)的这篇博文,这可能会导致意外问题。 (请参阅“编译时与运行时 sin ”部分。)

这是Go中的一个相关问题吗? 还是出于其他原因限制了此用法?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtiopy6088 2019-03-21 20:58
    已采纳

    Go simply lacks the concept. There is no way of marking a function as pure (its return value depends only on its arguments, and it doesn't alter any kind of mutable state or perform I/O), there is no way for the compiler to infer pureness, and there's no attempt to evaluate any expression containing a function call at compile-time (because doing so for anything except a pure function of constant arguments would be a source of weird behavior and bugs, and because adding the machinery needed to make it work right would introduce quite a bit of complexity).

    Yes, this is a substantial loss, which forces a tradeoff between code with bad runtime behavior, and code which is flat-out ugly. Go partisans will choose the ugly code and tell you that you are a bad human being for not finding it beautiful.

    The best thing you have available to you is code generation. The integration of go generate into the toolchain and the provision of a complete Go parser in the standard library makes it relatively easy to munge code at build time, and one of the things that you can do with this ability is create more advanced constant-folding if you so choose. You still get all of the debuggability peril of code generation, but it's something.

    点赞 打赏 评论
  • duanqian1888 2019-03-21 20:39

    Go doesn't support initializing a constant with the result of a function. Functions are called at runtime, not at compile time. But constants are defined at compile time.

    It would be possible to make exceptions for certain functions (like math.Sin for example), but that would make the spec more complicated. The Go developers generally prefer to keep the spec simple and consistent.

    点赞 打赏 评论

相关推荐 更多相似问题