Skip to content

cmd/compile: fail to infer type with only one valid solution #50212

Closed
@Ludonope

Description

@Ludonope

What version of Go are you using (go version)?

$ go version
go version go1.18beta1 darwin/amd64

Does this issue reproduce with the latest release?

Yes

What did you do?

I'm trying to make some sort of Nullable constraint which would indicate if that type can be set to nil or not.

Right now I'm only trying to detect pointers and slices.

One way to detect a pointer type (which works) is the following:

type Ptr[T any] interface {
	~*T
}

func SetNil[U any, T Ptr[U]](val T) {
	val = nil
}

func main() {
    a := 0
    SetNil(&a)
}

It can also be done with slice type:

type Slice[T any] interface {
	~[]T
}

func SetNil[U any, T Slice[U]](val T) {
	val = nil
}

func main() {
    SetNil([]int{})
}

However if I try to combine those into a Nullable constraint the type inference breaks for U.

https://go.dev/play/p/SbBJnOUeFVP?v=gotip

Providing the types U and T explicitly works tho.

What did you expect to see?

I'm expecting the compiler to properly infer Uand T types. As there are multiple options for T but only one of them is valid, it should be able to try to deduce U just like it does when using the Ptr[T] or Slice[T] constraint.

What did you see instead?

./prog.go:20:8: cannot infer U (prog.go:15:13)

Go build failed.

You should be able to reproduce this with the go.dev/play link provided above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions