Skip to content

cmd/compile: Cannot return a defined generic type as a generic type #54929

@godcong

Description

@godcong

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

$ go version go1.19.1 windows/amd64

Does this issue reproduce with the latest release?

yes

What did you do?

type Command struct {
	Path string   
	Env  []string
	Cmd  string 
	Args []string
}

type Rename struct {
	Path   string 
	Regexp string 
	Target string 
}

//...

type Ruler interface {
	Command | Replace | Remove | Rename | Copy | Make
}

type Action struct {
        Type      Type  //Enumeration values bound to Ruler types
	Commands []Command 
	Replaces []Replace 
	Removes  []Remove 
	Renames  []Rename 
	Copies   []Copy   
	Makes    []Make   
}


func getRulers[R Ruler](action Action) []R {
	switch action.Type {
	case TypeCommand:
		return action.Commands
	case TypeReplace:
		return action.Replaces
	case TypeRemove:
		return action.Removes
	case TypeRename:
		return action.Renames
	case TypeCopy:
		return action.Copies
	case TypeMake:
		return action.Makes
	}
	return nil
}

What did you expect to see?

If Ruler is the Command type, then the []R I return is []Command
But the compiler does not recognize this

.\action.go:48:10: cannot use action.Commands (variable of type []Command) as type []R in return statement

Now I can only force the type conversion to R:

func castRuleCommand[R Ruler](r []Command) []R {
	return *(*[]R)(unsafe.Pointer(&r))
}

What did you see instead?

The code can be compiled

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions