v icon indicating copy to clipboard operation
v copied to clipboard

cgen: fix match with option type

Open felipensp opened this issue 2 years ago • 1 comments

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 |     }

felipensp avatar Mar 19 '23 20:03 felipensp

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?

XiaoPangxie732 avatar Mar 20 '23 18:03 XiaoPangxie732

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?

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.

spytheman avatar Mar 20 '23 19:03 spytheman