Home > other >  Allow pass to func only pointer, not values
Allow pass to func only pointer, not values

Time:04-06

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.

CodePudding user response:

Yes you can use generics like this:

func Foo[T any](t *T){
…
}
  •  Tags:  
  • go
  • Related