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

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

Closed
godcong opened this issue Sep 7, 2022 · 1 comment
Closed

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

godcong opened this issue Sep 7, 2022 · 1 comment
Labels
compiler/runtime Issues related to the Go compiler and/or runtime. FrozenDueToAge

Comments

@godcong
Copy link

godcong commented Sep 7, 2022

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

@gopherbot gopherbot added the compiler/runtime Issues related to the Go compiler and/or runtime. label Sep 7, 2022
@seankhliao
Copy link
Member

This is working as intended, in your example if you R is instantiated to Command, then all your other return statements are invalid.

See also #45380

@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Sep 7, 2022
@golang golang locked and limited conversation to collaborators Sep 7, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
compiler/runtime Issues related to the Go compiler and/or runtime. FrozenDueToAge
Projects
None yet
Development

No branches or pull requests

3 participants