On Wed, Nov 13, 2024 at 8:59 AM Elad Gavra <gav...@gmail.com> wrote: > > I would like to create a non-pointer constraint for a generic function. > For example: > ``` > func F[T NonPtr](p T) { > // do something with p > } > ``` > Such that > ``` > F(MyStruct{}) // allowed > F(&MyStruct{}) // disallowed, compile time > ``` > I'm aiming to ensure, in compile-time, that a generic function, which is > intended to work with values only, cannot be misused by passing in a pointer. > (I can provide more context on my use case if needed.) While this could be > enforced with a custom linter, I feel this should be a built-in capability of > the language. From what I understand, though, this feature isn’t currently > supported. > > What do you think?
In general Go generics allow the program to say that the type must have a certain structure (see https://go.dev/blog/deconstructing-type-parameters) but Go does not permit the program to say that the type must _not_ have a certain structure. In general this hasn't been a big problem. It is of course possible to dynamically reject type structure at run time using the reflect package, but there is no way to do it statically. Personally I mostly think that is OK. One of the guidelines that Go follows is to encourage people to write code rather than write types. To me this falls into writing types. That said, if we do decide to add facilities for rejecting type structure, I don't think we should just add something to say "no pointers, please." We should have a more general approach that also allows us to say things like "no structs" or "no interface types." Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcU9a_0DFXo0hT-6S4qB%2Bn4n%2Bd9yijn2ppt_hd1DFW2SFw%40mail.gmail.com.