gpt4 book ai didi

Go fmt 为数学表达式生成格式不一致的结果

转载 作者:行者123 更新时间:2023-12-01 22:39:40 26 4
gpt4 key购买 nike

我的理解是 go fmt 应该生成可读且格式一致的代码。但是,我认为情况并非如此。

我输入了注释代码,然后 go fmt 返回了未注释的代码。为什么会崩溃 0.5*(y3-y0) ,但不是 0.5 * (y2 - y0) ?这怎么一致?而且,IMO,几乎每个空间都塌陷的返回线是可读性灾难。

不一致是错误吗?
有没有办法让 go fmt 单独留下一些行(如返回行)?

func cubicInterpolate(x, y0, y1, y2, y3 float64) float64 {
// 4-point, 3rd-order Hermite (x-form)
// c0 := y1
// c1 := 0.5 * (y2 - y0)
// c2 := y0 - 2.5 * y1 + 2. * y2 - 0.5 * y3
// c3 := 1.5 * (y1 - y2) + 0.5 * (y3 - y0)
//
// return ((c3 * x + c2) * x + c1) * x + c0

c0 := y1
c1 := 0.5 * (y2 - y0)
c2 := y0 - 2.5*y1 + 2.*y2 - 0.5*y3
c3 := 1.5*(y1-y2) + 0.5*(y3-y0)

return ((c3*x+c2)*x+c1)*x + c0
}

最佳答案

这记录在 go source code ;目的是使运算符优先级明确。例如在您的示例中 y0 - 2.5*y1 + 2.*y2 - 0.5*y3乘法将在减法之前执行,所选择的格式一目了然。

回答你的问题;这不是错误;确实quite a bit of effort被放入格式化。您不能从格式中排除一行;这是设计使然,如 FAQ 中所述,目的是执行layont规则:

gofmt is a pretty-printer whose purpose is to enforce layout rules; it replaces the usual compendium of do's and don'ts that allows interpretation.



以下是 go/printer/nodes.go 的格式化摘录详细说明了格式化规则:

Format the binary expression: decide the cutoff and then format. Let's call depth == 1 Normal mode, and depth > 1 Compact mode. (Algorithm suggestion by Russ Cox.)

The precedences are:
5 * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 ||

The only decision is whether there will be spaces around levels 4 and 5. There are never spaces at level 6 (unary), and always spaces at levels 3 and below.

To choose the cutoff, look at the whole expression but excluding primary expressions (function calls, parenthesized exprs), and apply these rules:

  1. If there is a binary operator with a right side unary operand that would clash without a space, the cutoff must be (in order):
   /* 6   
&& 6
&^ 6
++ 5
-- 5

(Comparison operators always have spaces around them.)

  1. If there is a mix of level 5 and level 4 operators, then the cutoff is 5 (use spaces to distinguish precedence) in Normal mode and 4 (never use spaces) in Compact mode.

  2. If there are no level 4 operators or no level 5 operators, then the cutoff is 6 (always use spaces) in Normal mode and 4 (never use spaces) in Compact mode.

关于Go fmt 为数学表达式生成格式不一致的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023245/

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