Allow pass to func only pointer, not values


I want to allow pass to func only pointer to a struct, restrict values. Is it possible?

What I want to do:

Foo(&Bar{}) // allowed
Foo(Bar{}) // IDE/compilation error

Actually i’m using signature like func Foo(bar any) which allows pass to the function any interface and type, of course, so in some cases it can cause problems.

Amount of types, which can passed to this function is should be not limited, and I don’t want to use specific interface etc. Maybe this can be achieved with generics? But I’m not sure how to do it correctly.

I’m use go 1.18.


Yes you can use generics like this:

func Foo[T any](t *T){

Answered By – Tiago Peczenyj

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.