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

generics: Confusion between interfaces and constraints #46359

Closed
millergarym opened this issue May 25, 2021 · 5 comments
Closed

generics: Confusion between interfaces and constraints #46359

millergarym opened this issue May 25, 2021 · 5 comments
Labels
FrozenDueToAge generics Issue is related to generics WaitingForInfo Issue is not actionable because of missing required information, which needs to be provided.

Comments

@millergarym
Copy link

Is there any way of using constraints as return types where the value being returned is instantiated in the body of the function?

Or does this fall into Possible future step: permitting constraints as ordinary interface types?

type iors interface {
	type int, string
}

func Bar() iors {
  return int(1)
}

func Foo[T iors]() T {
  return int(1)
}

From https://go2goplay.golang.org/p/S5ppLsCtMPv

type checking failed for main
prog.go2:12:10: cannot use int(1) (constant 1 of type int) as T value in return statement
prog.go2:7:12: interface contains type constraints (int, string)
@millergarym
Copy link
Author

It's becoming clearer.
The following works.

https://go2goplay.golang.org/p/eGjeoSCo7Ua

type iors interface {
	type int, string
}

func Foo[T iors]() (t T) {
  fmt.Printf("%T\n", t)
  x := 1
  return *(*T)(unsafe.Pointer(&x))
}

func main() {
	a := Foo[int]()
	fmt.Printf("%T(%v)\n", a, a)
}

@millergarym
Copy link
Author

Related to #45380
Type switches on return types might be nice.

func Foo[T iors]() (t T) {
	switch t.(type) {
	  ...
	}
}

@ianlancetaylor
Copy link
Member

I don't see any action to take here.

Discussion about the generics proposal should take place on golang-nuts. Thanks.

@ianlancetaylor ianlancetaylor added generics Issue is related to generics WaitingForInfo Issue is not actionable because of missing required information, which needs to be provided. labels May 25, 2021
@millergarym
Copy link
Author

@ianlancetaylor thanks for the response / triage.
I'm pushing on using generics as sumtypes, it's clear they're not there yet.

@ianlancetaylor
Copy link
Member

There is some discussion at #45346. But, yes, support for sum types is intentionally omitted.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
FrozenDueToAge generics Issue is related to generics WaitingForInfo Issue is not actionable because of missing required information, which needs to be provided.
Projects
None yet
Development

No branches or pull requests

3 participants