Home > Backend Development > Golang > Cannot use struct as type struct {...}

Cannot use struct as type struct {...}

WBOY
Release: 2024-02-10 19:06:09
forward
714 people have browsed it

不能使用 struct 作为类型 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.

Question content

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

}
Copy after login

I get this compilation error:

<code>
Cannot use 'iterable' (type Iterable[int]) as the type struct {...}
</code>
Copy after login

I thought struct types should allow this type of thing - where did I go wrong?

Solution

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!

Related labels:
source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template