Skip to content

v: allow sumtype init by variant comptime var T(v) / SumType(v)#22664

Merged
spytheman merged 2 commits intovlang:masterfrom
felipensp:allow_sumtype_init_by_name
Oct 27, 2024
Merged

v: allow sumtype init by variant comptime var T(v) / SumType(v)#22664
spytheman merged 2 commits intovlang:masterfrom
felipensp:allow_sumtype_init_by_name

Conversation

@felipensp
Copy link
Copy Markdown
Member

@felipensp felipensp commented Oct 26, 2024

This PR allows to initialize Sumtype through its variant comptime types.

e.g.

type Sum = int | string

fn get[T](val T, type_name string) T {
	$if T is $sumtype {
		$for v in val.variants {
			if type_name == typeof(v.typ).name {
				return T(v)
			}
		}
	}
	return T{}
}

fn main() {
	dump(get(Sum{}, 'int')) // Sum(0)
	dump(get(Sum{}, 'string')) // Sum('')
}

Huly®: V_0.6-21113

@felipensp felipensp changed the title v: allow sumtype init by name (comptime feature) v: allow sumtype init by name T(v)/SumType(v) (comptime feature) Oct 26, 2024
@felipensp felipensp changed the title v: allow sumtype init by name T(v)/SumType(v) (comptime feature) v: allow sumtype init by name T(v) / SumType(v) (comptime feature) Oct 26, 2024
@felipensp felipensp changed the title v: allow sumtype init by name T(v) / SumType(v) (comptime feature) v: allow sumtype init by variant comptime var T(v) / SumType(v) (comptime feature) Oct 26, 2024
@felipensp felipensp changed the title v: allow sumtype init by variant comptime var T(v) / SumType(v) (comptime feature) v: allow sumtype init by variant comptime var T(v) / SumType(v) Oct 26, 2024
@felipensp felipensp marked this pull request as ready for review October 26, 2024 15:11
Copy link
Copy Markdown
Contributor

@spytheman spytheman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent work.

@spytheman spytheman merged commit 731d07d into vlang:master Oct 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants