Home >Backend Development >Golang >Cannot use struct as type struct {...}
php editor Xiaoxin will introduce an important note in this article: In PHP, you cannot use "struct" as a type. This is due to limitations of the PHP language itself, which does not support "struct" type definitions similar to those in C language. In PHP, we can use classes to define custom data structures, as well as related properties and methods. By using classes, we can operate data more flexibly and powerfully, and implement more complex logic and functions. Therefore, when writing PHP code, remember to avoid using "struct" as a type definition and use classes instead. This can better comply with the characteristics and specifications of the PHP language, making the code more readable, understandable and maintainable.
I have this code:
type Iterable[T any] struct { Val T End T Next func() (bool, T) } func acceptStructWithNext[T any](r struct{ Next func() (bool, T) }) { fmt.Println(r) } func main() { iterable := Iterable[int]{ Val: 0, End: 100, Next: func() (bool, int) { return true, 0 }, } acceptStructWithNext[int](iterable) // error is here }
I get this compilation error:
<code> Cannot use 'iterable' (type Iterable[int]) as the type struct {...} </code>
I thought struct types should allow this type of thing - where did I go wrong?
Yes, but Go doesn't have "struct types". To some extent, the benefits of structural types are obtained through the implicit satisfaction rules of interfaces. But this only works for interface.
Please refer to https://www.php.cn/link/2a2f98d3597419498e4d734d8c2dd106
Assume that Go will have struct types like textbook struct types.
The above is the detailed content of Cannot use struct as type struct {...}. For more information, please follow other related articles on the PHP Chinese website!