Type parameters on another line

117 views
Skip to first unread message

josvazg

unread,
Aug 1, 2020, 1:49:33 PM8/1/20
to golang-nuts
Let me know if this or something similar was already proposed and rejected for some reason but otherwise...

What if instead of trying to cram all into a single line we use a previous line before the function or type definition explaining how the type parameter aliases are to be interpreted. Like this:

```
types T Stringify
func Stringify(s []T) (ret []string) {
   ...
}
```
The prefix line:
```
types T Stringify
```
Only applies to the next code block.

IMHO this is more readable, still easy to parse and does not require to overload parenthesis or other punctuation for adding type parameters.

Issues with this approach:

You need to look at at least two lines to understand an expression fully.
  • Is that such a big deal? I mean when an interface is mentioned you still need to check that interface definition to fully get it.
  • Also isn't it worse the mess the cramming together makes?
  • Following conventions like T or T1, T2 and such you usually still "read" the expression without the types lines.
A new keyword `types` is required.
  • Is it ambiguous vs `type`? We could use another name, but this actually mean `typeParams` or `typeAliases`... usually keywords are single words without camel-case.
  • Again, is it such a big deal compared to the alternative?

## Sample translated original proposal samples

This:
```
func Print2Same(type T)(s1 []T, s2 []T) { ... }
```

Becomes:
```
types T
func Print2Same(s1 []T, s2 []T) { ... }
```

And so on:
```
types S Stringer, P Plusser
func ConcatTo(s []S, p []P) []string {
...
}
```

```
types L interface{}, T Stringer
func StrAndPrint(labels []L, vals []T) {
...
}
```

```
// Stringify2 converts two slices of different types to strings,
// and returns the concatenation of all the strings.
types T1, T2 Stringer
func Stringify2(s1 []T1, s2 []T2) string {
```

```
// Vector is a name for a slice of any element type.
types T
type Vector []T
```

```
// List is a linked list of values of type T.
types T
type List struct {
```


Ian Lance Taylor

unread,
Aug 1, 2020, 2:30:26 PM8/1/20
to josvazg, golang-nuts
Your examples don't seem to show any uses of generic types or functions.

I think it's a nice feature of the current design draft that the
syntax used to declare a generic type or function is very similar to
the syntax used to use a generic type or function. The declaration is
List(type T), and the use is List(int).

Ian

Jose Luis Vazquez

unread,
Aug 2, 2020, 1:22:14 PM8/2/20
to Ian Lance Taylor, golang-nuts
Thanks!

I see your point. I guess that is the main reason the type parameters mapping needs to be in the same declaration line.

Still, for generic types it is ok, but for generic functions it feels a bit too much stuff crammed into the signature line.

Thanks again for explaining!

Jose
Reply all
Reply to author
Forward
0 new messages