英文:
Can this Go code be refactored?
问题
只使用一个if
语句,不使用else
、switch
和简写的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 < 85 {
fmt.Println("WheelPos < 85",Color(WheelPos*3, 255-WheelPos*3, 0))
} else if WheelPos < 170 {
WheelPos -= 85
fmt.Println("WheelPos >= 85",Color(0, WheelPos*3, 255-WheelPos*3))
} else {
WheelPos -= 170
fmt.Println("WheelPos > 170",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 < 255; i++ {
Wheel(i)
}
}
The Color function is defined as such:
func Color(r uint32, g uint32, b uint32) uint32 {
return (r << 16) | (g << 8) | b
}
I have started off with something like so:
func Wheel(WheelPos uint32) {
if (WheelPos < 85) || (WheelPos >= 85) || (WheelPos > 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
这是可能的:你可以为>170
的情况创建一个if语句,然后定义一个包含170个函数指针的数组,并对其他两种情况使用索引操作。不过,我无法想到一个合理的情况,这种解决方案比你已经有的解决方案更好。
英文:
It is technically possible: you could create an if statement for the >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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论