v
v copied to clipboard
cgen: fix match with option type
Fix #17711
fn main() {
mut a := ?int(12)
match a? {
12 { println(a) }
//none { println('none') }
else { println('else') }
}
match a {
none { println('none') }
else { println('else') }
}
a = none
match a {
none { println('none') }
else { println('else') }
}
mut b := ?string('aaa')
match b? {
'aaa' { println(b) }
else { println('else') }
}
match b {
none { println('none') }
else { println('else') }
}
b = none
match b {
none { println('none') }
else { println('else') }
}
}
Added error when using option type without unwrap to check against value different of none:
bug.v:4:8: error: `match` expression with Option type only checks against `none`, to match its value you must unwrap it first `var?`
2 | mut a := ?int(12)
3 | match a {
4 | 12 { println(a) }
| ~~~~~~~~~~
5 | else { println('else') }
6 | }
Just curious. Why match expression with Option type only checks against none? Is matching its value and checking against none at the same time a bad idea? Why?
Just curious. Why
matchexpression with Option type only checks againstnone? Is matching its value and checking againstnoneat the same time a bad idea? Why?
Because the value needs to be unwrapped first. Here:
b = none
match b {
none { println('none') }
else { println('else') }
}
the else branch could have access to the unwrapped values of b (if it was not none).
The match itself however has access only to the wrapped value of b, which can be either none or valid value of the type string.