Skip to content

Set variable through generic function to a field with Any{} interface compile returns error #19010

@helto4real

Description

@helto4real

Describe the bug

I am trying to build an IoC container in V. This means I need to store any object with any type. For this I an using the empty interface. I want to register the object using a generic function. Hypothetical usage is below.

fn main()
{
    mut container := new_container()
    container.register[SomeStruct] = &SomeStruct{}
    container.register[SomeInterface] = &SomeStruct{}

    s := container.get[SomeStruct]()
    // This is currently not possible and returns error from checker
    i:= container.get[SomeInterface]()
}

Expected Behavior

Expected the following line to work:
I expected it to be possible to store any object using a generic function that provides an interface as generic type and any object that confirms to that interface.

i:= container.get[SomeInterface]()

Se simplified full reproduction example to further understand the code.

Current Behavior

The last line gives :

error: cannot implement interface `Any` with a different interface `AInterface`
   25 | pub fn (c &Container) get[T]() !&T
   26 | {
   27 |     if c.any is T {
      |                 ^
   28 |         return c.any
   29 |     }

Reproduction Steps

Just compile sample below and the get the compiler error.

interface Any{}

interface AInterface
{
	a int
}

struct StructA
{
	mut:
		a int
}

struct Container
{
	mut:
	 any Any
}

pub fn (mut c Container) set[T](obj Any)
{
	c.any =obj
}
pub fn (c &Container) get[T]() !&T
{
	if c.any is T {
		return c.any
	}
	return error("Ops")
}
fn main()
{
	a := &StructA{a: 100}
	b := &StructA{a: 200}
	mut c := &Container{any: a}

	if mut c.any is AInterface
	{
		println(c.any.a)
	}
	// Working
	c.set[StructA](b)
	// Working
	c.set[AInterface](b)
	// Working
	d:= c.get[StructA]()!
	// This is not working error: cannot implement interface `AInterface` with a different interface `Any`
	e := c.get[AInterface]()!
	println(d)
}

Possible Solution

Probably a checker bug. If it is by design I could argue that this feature would be great to be able to use generics to store and retrieve any object by it's type including interface types.

Additional Information/Context

No response

V version

V 0.4.0 1c2b4e7

Environment details (OS name and version, etc.)

Linux Ubuntu 20.04 (Windows-WSL)

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugThis tag is applied to issues which reports bugs.Generics[T]Bugs/feature requests, that are related to the V generics.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions