Home > Backend Development > Golang > Why Does Go's Generic Code Fail with 'cannot use variable of type *T as type in argument'?

Why Does Go's Generic Code Fail with 'cannot use variable of type *T as type in argument'?

Barbara Streisand
Release: 2024-12-13 20:34:21
Original
903 people have browsed it

Why Does Go's Generic Code Fail with

Understanding the Error in Generic Code

In Go, a common error when working with generics is "cannot use variable of type *T as type in argument" when trying to pass a pointer to a generic type to a function. This occurs because the generic type parameter T is not equivalent to the constraint type used to restrict it.

Understanding Type Constraints

In the provided code, the interface FooBar is defined as a union of two types foo and bar. This means that any type implementing the method a() string can be assigned to a FooBar interface. However, the generic type parameter T used in the function blah is not implicitly equivalent to FooBar.

Implementing Methods on Pointers

Furthermore, the methods in the types foo and bar are implemented on pointer receivers (foo and bar). This means that the method a() string is actually defined for pointers to these types, not the types themselves.

Resolving the Error

To resolve the error, you need to either assert that the generic type parameter T implements the stringer interface or explicitly define the union of types in the constraint itself.

Asserting Stringer Implementation

func blah[T FooBar]() {
    t := new(T)
    do(any(t).(stringer))
}
Copy after login

However, this approach foregoes type safety and could lead to runtime panics.

Explicitly Defining the Union

type FooBar[T foo | bar] interface {
    *T
    stringer
}

func blah[T foo | bar, U FooBar[T]]() {
    var t T
    do(U(&t))
}
Copy after login

This approach preserves type safety and allows you to initialize the generic type parameter T to a non-nil value.

Conclusion

Understanding the relationship between generic type parameters and their constraints is crucial to using generics effectively in Go. By carefully defining interfaces and constraints, you can enforce type safety and avoid runtime errors.

The above is the detailed content of Why Does Go's Generic Code Fail with 'cannot use variable of type *T as type in argument'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template