这段 Go 代码可以进行重构吗?

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

Can this Go code be refactored?

问题

只使用一个if语句,不使用elseswitch和简写的if-else符号,可以这样修改:

func Wheel(WheelPos uint32) {
    if WheelPos < 85 {
        fmt.Println("WheelPos < 85", Color(WheelPos*3, 255-WheelPos*3, 0))
    }
    if WheelPos >= 85 && WheelPos < 170 {
        WheelPos -= 85
        fmt.Println("WheelPos >= 85", Color(0, WheelPos*3, 255-WheelPos*3))
    }
    if WheelPos >= 170 {
        WheelPos -= 170
        fmt.Println("WheelPos >= 170", Color(0, 255-WheelPos*3, WheelPos*3))
    }
}

main函数中的循环调用如下:

func main() {
    var i uint32
    for i = 0; i < 255; i++ {
        Wheel(i)
    }
}

Color函数的定义如下:

func Color(r uint32, g uint32, b uint32) uint32 {
    return (r << 16) | (g << 8) | b
}

我已经根据你的要求进行了翻译,如果还有其他问题,请随时提问。

英文:

Using only 1 'if' statement and no 'else' & no switch & no shorthand notation for if-else?

    // Original function
    func Wheel(WheelPos uint32) {
        if WheelPos &lt; 85 {
	        fmt.Println(&quot;WheelPos &lt; 85&quot;,Color(WheelPos*3, 255-WheelPos*3, 0))
        } else if WheelPos &lt; 170 {
	        WheelPos -= 85
	        fmt.Println(&quot;WheelPos &gt;= 85&quot;,Color(0, WheelPos*3, 255-WheelPos*3))
        } else {
	        WheelPos -= 170
	        fmt.Println(&quot;WheelPos &gt; 170&quot;,Color(0, 255-WheelPos*3, WheelPos*3))
        }
    }

The above function is called in the main inside a for loop like so:

    func main() {
        var i uint32
        for i = 0; i &lt; 255; i++ {
	        Wheel(i)
        }
    }

The Color function is defined as such:

    func Color(r uint32, g uint32, b uint32) uint32 {
        return (r &lt;&lt; 16) | (g &lt;&lt; 8) | b
    }

I have started off with something like so:

    func Wheel(WheelPos uint32) {
        if (WheelPos &lt; 85) || (WheelPos &gt;= 85) || (WheelPos &gt; 170) {
         // logic....
        }
    }

答案1

得分: 1

我不认为你可以如何重构代码,并且保持清晰和表达能力。

如果你只有三种情况要考虑,将它们分别放在三个独立的if/else语句中是编写这些情况的最简单方式。

英文:

I don't see how you would refactor the code, and somehow keep it clear and expressive enough.

If you have only three cases to consider, making them in three separate if/else is the easiest way to code those cases.

答案2

得分: 0

这是可能的:你可以为&gt;170的情况创建一个if语句,然后定义一个包含170个函数指针的数组,并对其他两种情况使用索引操作。不过,我无法想到一个合理的情况,这种解决方案比你已经有的解决方案更好。

英文:

It is technically possible: you could create an if statement for the &gt;170 case, then define an array of 170 function pointers and use an index operation for the other two cases. I can't think of a reasonable case where this solution is actually better than the one you already have though.

huangapple
  • 本文由 发表于 2014年9月12日 18:25:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/25806133.html
匿名

发表评论

匿名网友

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

确定