Hacker News new | ask | show | jobs
by bruce343434 1652 days ago
How does Go handle the ambiguity between [] meaning generics and [] also meaning array?
2 comments

You can use optional(?) parenthesis to make it extra clear.

[]MyContainer[T] // slice of generic struct or interface

can/must be written as

[](MyContainer[T])

but ([]MyContainer)[T] isn't a valid use of generics anyways.

What about accesses? Seems like this would require at least some context in the parser. And what about the human parser? Do you get confused between arrays, array accesses, templates? Or do you get used to it?

    T int = 5
    myarray[T]
'T' is a completely normal identifier, it is merely the conventional one used as a type parameter. But you can also use Type, MyType, etc instead of T as that parameter identifier.

The compiler can easily detect if the thing in the [] is a int or type.

In most cases there is no parsing ambiguity. In the cases where there are, you need to use parenthesis to clarify.