Skip to content

cgen: fix interface generic smartcast - #20609

Merged
spytheman merged 2 commits into
vlang:masterfrom
felipensp:fix_interface_generic
Jan 23, 2024
Merged

spytheman merged 2 commits into
vlang:masterfrom
felipensp:fix_interface_generic

Conversation

@felipensp

Copy link
Copy Markdown
Member

Fix #20590

fn cast_interface[T, U](u U) T {
	$if U is $interface {
		if u is T {
			return u
		} else {
			panic('expected t to be ${typeof[T]().name}, got ${typeof[U]().name}')
		}
	} $else {
		$compile_error('not an interface')
	}
}

interface Foo {
	f()
}

struct Bar {}

fn (bar Bar) f() {}

struct Baz {}

fn (baz Baz) f() {}

fn (_ Bar) g() int {
	return 0
}

fn (_ Baz) g() int {
	return 1
}

fn f(foo Foo) int {
	if foo is Bar {
		return cast_interface[Bar, Foo](foo).g()
	}
	if foo is Baz {
		return cast_interface[Baz, Foo](foo).g()
	}
	return -1
}

fn test_main() {
	assert f(Bar{}) == 0
	assert f(Baz{}) == 1
}

@felipensp
felipensp marked this pull request as ready for review January 22, 2024 11:18

@spytheman spytheman left a comment

Copy link
Copy Markdown
Contributor

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 2874e7c into vlang:master Jan 23, 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.

cgen doesn't unwrap smartcasted interface value

2 participants