Trying to avoid writing too many returns in if/else or match. #22565
-
The combination of objects with options and created within a function with a single struct Number {
natural ?string
integer string
}
fn number(n int) Number {
return if n >= 0 { // a single return here
Number{ natural:'${n}', integer:'${n}' }
} else {
Number{ integer:'${n}' }
}
}
fn main() {
for n in [1,0,-1] {
println('${number(n)}')
}
} https://play.vlang.io/p/78094800a4 The problem:
A workaround is to use a fn number(n int) Number {
if n >= 0 {
return Number{ natural:'${n}', integer:'${n}' } // a return here
} else {
return Number{ integer:'${n}' } // another return here
}
} The expected output:
I have found this problem more than once trying to avoid writing "too many" But now I wonder if is worth to solve the issue mentioned above for this particular case and then later more complex objects could cause new problems, or just encourage to program "the easy way" as in the workaround. Thoughts? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
PR added to fix this issue #22578 |
Beta Was this translation helpful? Give feedback.
PR added to fix this issue #22578