Understanding the "Cannot Use Variable of Type *T as Type Stringer in Argument" Error in Go Generics
In the code snippet provided, you're attempting to generically invoke a function do that expects a parameter of type stringer, but you're passing a pointer to a type parameter T instead.
The Go compiler is raising an error because:
Fixing the Issue
There are two main approaches to resolving this issue:
1. Assert Type Safety with Type Assertion (Less Optimal)
2. Redefine Constraint and Customize Generics (Preferred)
Revised Code:
type FooBar[T foo | bar] interface { *T stringer } func blah[T foo | bar, U FooBar[T]]() { var t T do(U(&t)) } func main() { blah[foo]() }
In this revised code:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3