Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot directly use method from generic embedded struct #19968

Closed
Casper64 opened this issue Nov 22, 2023 · 0 comments · Fixed by #20011
Closed

Cannot directly use method from generic embedded struct #19968

Casper64 opened this issue Nov 22, 2023 · 0 comments · Fixed by #20011
Labels
Bug This tag is applied to issues which reports bugs.

Comments

@Casper64
Copy link
Member

Casper64 commented Nov 22, 2023

Describe the bug

When embedding a generic struct V doesn't recognize a method on the embedded struct without specifiying the struct name:

This doesn't work:

s.use(test_handler)

But this does:

s.Collector.use(test_handler)

Reproduction Steps

pub type Handler[T] = fn (mut T) bool

struct Collector[T] {
mut:
	handlers []Handler[T]
}

pub fn (mut c Collector[T]) use(func Handler[T]) {
	c.handlers << func
}

pub struct Context {}

fn test_handler(mut ctx Context) bool {
	println('from test_handler!')
	return true
}

pub struct MainStruct {
	Collector[Context]
}

fn main() {
	mut s := MainStruct{}
	
	s.use(test_handler)

	// 	no need to specify the embedded struct for fields
	assert s.handlers.len == 1
}

Expected Behavior

No error

Current Behavior

code.v:26:4: error: unknown method or field: MainStruct.use
24 | mut s := MainStruct{}
25 |
26 | s.use(test_handler)
| ~~~~~~~~~~~~~~~~~
27 | // s.Collector.use(test_handler)
28 |

Possible Solution

I thought maybe I'd have to make MainStruct generic for it to work, but V also doesn't like this:

pub struct MainStruct[T] {
	Collector[T]
}

fn main() {
	mut s := MainStruct[Context]{}
	
	s.use(test_handler)
}

Error:

code.v:24:11: error: could not infer generic type `T` in generic struct `Collector[T]`
   22 | 
   23 | fn main() {
   24 |     mut s := MainStruct[Context]{}
      |              ~~~~~~~~~~~~~~~~~~~~~
   25 |     
   26 |     s.use(test_handler)

Additional Information/Context

It is possible to directly use fields from that embedded struct, only methods fail:

assert s.handlers.len == 1

V version

V 0.4.3 25777bd.7519f91

Environment details (OS name and version, etc.)

Linux

Note

You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug This tag is applied to issues which reports bugs.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant