Matching in V

Posted by yhuang
Last Edited by dhonx
Public (Editable by Users)
V
None
Edit
// A match statement is a shorter way to write a sequence of if - else statements.
// When a matching branch is found, the following statement block will be run, and the final expression will be returned.
// The else branch will be evaluated when no other branches match.
os := 'windows'
print('V is running on ')
match os {
	'darwin' { println('macOS.') }
	'linux'  { println('Linux.') }
	else     { println(os) }
}

number := 1
s := match number {
	1    { 'one' }
	2    { 'two' }
	else { 
		println('this works too')
		'many' 
	}
}

// A match statement can also be used to branch on the variants of an enum by using the shorthand .variant_here syntax.
enum Color {
	red
	blue
	green
}
fn is_red_or_blue(c Color) bool {
	return match c {
		.red { true }
		.blue { true }
		else { false }
	}
}