Skip to content
This repository was archived by the owner on Sep 20, 2022. It is now read-only.
This repository was archived by the owner on Sep 20, 2022. It is now read-only.

Type Parameter Constraints #11

Description

@jeromefroe

Hi! I was wondering what your thoughts were on supporting type constraints so that one could require that a type T must implement a certain interface. For example (playground):

package main

import "fmt"

type Describer interface {
 	Describe() string
}

type A struct {}

func (a A) Describe() string { return "A" }

func Description[T](t T) string {
	return t.Describe()
}

func main() {
      	a := A{}
	fmt.Println(Description[A](a))
}

This program fails to compile with the following error:

main.go:14:9: invalid operation: t (variable of type T) has no field or method Describe

which makes sense since we don't require that the type T in Description implements Describer so we can't call Describe on t. But we could perhaps constrain T to require that it implements Describer:

func Description[T: Describer](t T) string {
	return t.Describe()
}

Then we could safely call Describe because the compiler will enforce that all types T implement Describer. Supporting such a feature might make it possible to use generics in more places where interfaces are used currently. Anyway, just interested in what your thoughts were. Thanks!

P.S. This project is really cool!

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions