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

proposal: Support for a feature in Generics like Typescript has <T extends {name: string}> #51993

Closed
Ammce opened this issue Mar 28, 2022 · 2 comments

Comments

@Ammce
Copy link

Ammce commented Mar 28, 2022

Hi there,

I have been trying out the Golang Generics, and I love them. Great work! However, one thing that I am using a lot in Typescript seems to be missing, or I can not find an answer anywhere. I would love to be able to create a function that accepts a generic struct element with a minimum requirement of a property that needs to be passed to the function. Something like that exists in a Typescript where <T extends {name: string}>

Let's analyze the code below. In the function printNameAndAge, on the place where I put (*extends*) placeholder, I think it would be awesome if somehow we could specify that it is a minimum property of a struct requirement for this function as I will work only with Age and Name

Note: I have seen many workarounds with Interfaces for this, by implementing a function for each property, and all of that seems too messy for such a simple requirement. Once again, I might miss it, or missed the point completely about it, as I have just started exploring Generics in Go, and I am coming from Typescript world.

import "fmt"

type User struct {
	Name   string
	Age    int
	Height float32
}

type Car struct {
	Age   int
	Name  string
	Model string
}

type NameAndAge struct {
	Name string
	Age  int
}


func printNameAndAge[T (*extends*) NameAndAge](u T) {
	fmt.Println(u.Name)
	fmt.Println(u.Age)
}

func main() {
	newUser := User{
		Name:   "John",
		Age:    24,
		Height: 186,
	}
	newCar := Car{
		Name:  "Series 3",
		Age:   1,
		Model: "BMW",
	}

	printNameAndAge(newUser)
	printNameAndAge(newCar)

}
@Ammce Ammce added the Proposal label Mar 28, 2022
@gopherbot gopherbot added this to the Proposal milestone Mar 28, 2022
@DeedleFake
Copy link

Not for or against, but I think that a more Go-like syntax would be to make it part of the type set system. For example,

type NameAndAge interface {
  ~struct {
    Name ~string // Being able to use ~ on the fields might be overkill...
    Age ~int
    ... // Literal ... in the code to indicate that more fields are allowed. Possibly unnecessary.
  }
}

@seankhliao
Copy link
Member

Duplicate of #51259

@seankhliao seankhliao marked this as a duplicate of #51259 Mar 28, 2022
@golang golang locked and limited conversation to collaborators Mar 28, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants