-
Notifications
You must be signed in to change notification settings - Fork 17.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: Go 2: generic native types (GNTs) #32863
Comments
Also compare with #32862 just prior to this one. |
It is some like this one without the outer |
One of the goals of generics is to permit people to write type safe containers that are not already provided in the language. A typical example would be a concurrent hash map, such as a type safe version of Am I correct in thinking that this is much the same as https://gist.github.com/rcoreilly/bfbee2add03c76ada82810423d81e53d ? |
@ianlancetaylor Yep I'm submitting an updated, more fully worked-through version of that gist idea here in order to get a complete, considered evaluation of this idea from the entire team, per the proposal process description. Here is my response to that question from the go-nuts email list (you didn't reply to this response so I don't know if it is satisfactory or not?) you can do any valid map operation on the generic type “map”, so at a minimum it seems like you could just add an appropriate mutex around each of the different operations, using a struct interface: type SafeMap struct interface {
mu sync.RWMutex
m map
}
func (m *SafeMap) Store(k key(m.m), v elem(m.m)) {
m.mu.Lock()
if m.m == nil {
m.m = make(map[key(m.m)]elem(m.m))
}
m.m[k] = v
m.mu.Unlock()
}
… any concrete map that shares that struct interface type signature (i.e., the same field names and types) automatically gets the associated methods: // MySafeMap implements the SafeMap struct interface
type MySafeMap struct {
mu sync.RWMutex
m map[string]string
}
func MyFunc() {
m := MySafeMap{}
m.Store(“mykey”, “myval”) // at this point the compiler knows the concrete type of “m”, can compile Store
} Robert Engles replied:
To which I replied:
|
Thanks, I did see that discussion, and didn't reply further because I thought the point had been made. Sometimes you want a type-safe container that is entirely different. I think that is part of the 80%, not the 20%. |
I like this proposal. It adds minimal syntax complexities and zero emission of noises for generic code. It does not change much how Go1 code looks. |
@ianlancetaylor Have you considered that, as long as said container is composed out of existing container elements, GNTs would handle that case? How many containers would not have a map or slice as the underlying storage? Also, it would be possible to adopt this proposal on its own minimalist merits, and postpone a more "generic" generic solution, after real-world experience with how far this can go. It seems likely that anything that is "fully generic" is going to incur a significant syntactic penalty in terms of type specifiers and contracts, so perhaps it would be better to put that off until we can see to what extent it is really that valuable in real-world cases? And @typeless thanks for the support! |
The maps provided by the language don't permit you to specify a hash or equality function, so they are limited in how they handle keys. You can't implement a proper concurrent hashmap on the basis of maps or slices; you need a more complex data structure. I find these to be serious difficulties with this approach. Of course others may not agree. |
Not to belabor the point but if these features were deemed not important enough to include in the language itself then perhaps that indicates their status relative to the 80 / 20 tradeoff? Could we use some Go corpus stats to decide these kinds of questions - how frequently are those features actually used? |
This comment has been minimized.
This comment has been minimized.
Is it not possible to consider a solution for the subset of the problem? Seems that is the approach the |
This comment has been minimized.
This comment has been minimized.
@rcoreilly The language has a limited set of generic types. The generics problem is that Go provides no way for people to write generic code other than using that limited set. Any 80/20 tradeoff here, if there is one, doesn't have anything to do with what Go already provides. It has to do with a tradeoff among concepts that Go does not provide. I am suggesting that the ability to write compile-time-type-safe containers is part of the 80% that needs to be provided by any solution to the generics problem. The fact that Go does not provide such containers doesn't tell us anything about whether compile-time-type-safe containers are in the 80% or 20% of what Go does not provide.
I don't think I understand this question. Since Go does not provide these features, they are never used. |
@mikeschinkel We can consider steps that solve a subset of the problem, as long as there is a clear path forward to addressing more of the problem as we gain experience. The |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
@ianlancetaylor Not in reply to your reply. but as an additional comment. However, since this is off-topic of this proposal I am hiding it in a details section. Click to readI think everyone in the Go team understands that generics are a very hard problem to solve without recreating the complexity of generics in Java et.al. And I for one very much do not want Go to become so complex that its code is hard to reason about in order to add generics. One thing Go has done that is relatively unique in the realm of serious programming languages is provide builtin functions with features that a Go programmer cannot develop on their own, e.g. As such, it is my hope that the Go team will address most of the need for generics with builtin functions to handle the 80+% of use-cases. Here is my list of proposed new builtins:
I am assuming that the compiler could see all the above and be able to optimize it hence why there would be no need to qualify properties or methods. OTOH, for the Of course the names I chose are open for bikeshedding, but the functionality is really what I wanted to present. There maybe be one of two more that I have forgotten, but this is all I've got at the moment. The above would probably eliminate at least 80-90% of my needs for generics and it would probably reduce the number of lines of code in my codebases by 1/3 to 1/2 current size. |
This comment has been minimized.
This comment has been minimized.
@ianlancetaylor Haven't people written non-type-safe Also, in terms of a pathway to full generic types, it occurs to me that this overall approach could be extended as in Michal Straba's generics proposal to use the keyword |
I see, sure, that is worth asking. It's not a great comparison since interfaces generally require boxing values, so there is a real cost to building containers based on interfaces. So people avoid doing that. But it's worth asking. For example, can this proposal be used to build a compile-time-type-safe version of |
Yep definitely can do a compile-time-type-safe version of sync.Map -- when the |
I don't understand how that works. And looking back at your |
It is just a different way of achieving the same end result. Either you add new syntax to specify type parameters (following the paradigm used in C++ and other languages), or you name a concrete instantiation of a In other words, the move here is to adopt the idea that an abstract A drawback is that you need to come up with relevant names for the concrete instantiations (probably something better than But the advantage is that you can further customize the concrete type, just like something that implements an For many cases involving generic number or float types, e.g., the So anyway, yes this is definitely not the standard type-parameterized generics syntax, and this is also why I think it is likely to be the most "Go-like" of any of the existing proposals, most of which follow in that general type-parameter mold.. |
On 7/4/19, rcoreilly ***@***.***> wrote:
It is just a different way of achieving the same end result. Either you add
new syntax to specify type parameters (following the paradigm used in C++
and other languages), or you name a concrete instantiation of a `struct
interface` type (which seems like a more Go way to do it, following the
`interface` paradigm). In both cases, you are specifying the same
information.
Any chance you could explain by example?
Lucio.
|
When I say that I believe that any generics implementation must be able to support compile-time-type-safe containers, I mean that people must be able to write the code for a container once, and be able to instantiate that code many times for many different types. I think the ability to do that is a requirement for any generics proposal in Go. |
@typeless I'm not familiar with those GCC extensions so I'll have to look those up -- good prior art it seems! Regarding the unexported (lowercase) fields, there would have to be a rule that says that the unexported fields of a Then it is just a question of design preference whether to use unexported or exported field names, as it is currently. |
Looks like |
Perhaps it would be clearer to use a different keyword such as
It is also cleaner to have a single keyword instead of a sequence of two. |
Just saw the updated contracts proposal: https://go.googlesource.com/proposal/+/master/design/go2draft-contracts.md -- given that contracts can now only specify existing types, wouldn't it be simpler to just introduce sensible generic type categories in the first place, and do away with the need for the contract syntax and the type parameters! :) How many times will people specify random combinations of number types? Or generic functions that operate on string and number types? This seems like a lot of extra parentheses and syntax, for potentially rarely needed extra degrees of freedom.. |
Well, last September shortly after the first draft design for generics had been published, I wrote an alternative proposal which did use what I thought at the time were sensible 'type groups'. However, it later became clear that, with the integer groups, there were problems with the smaller types not being able to deal with untyped literals outside their range and, in later proposals, I came up with the idea of being able to exclude such types from those which would otherwise have satisfied the contract. When I look at the latest draft design, I think listing the types which can satisfy the contract is much simpler and more flexible (even if a trifle long-winded) than having predefined type groups though a standard contracts package can, of course, include the contracts which are most likely to be used in practice. |
Note that the only extra syntax for contracts is the ability to write an identifier after the list of type parameters. The extra parentheses are still there to list the type parameters. In exchange we get the ability to, for example, write a function that operators on either a |
@alanfo I remember some of that discussion which certainly inspired this current proposal. Within the context of the draft design, the ability to list types explicitly and also use predefined contracts that delineate the standard kinds of categories seems reasonable and is certainly more flexible than only having predefined categories. However, in the context of the present proposal, there is a much bigger potential benefit available by using generic type names ( |
@ianlancetaylor you should be able to write a lot of common functions that operate on slices of any type using the generic It should also be possible to extend the proposal to include generic types of the form I haven't looked into the guts of |
The problem with using the smaller integer types was not so much that they might overflow but that (to take an example from the current design draft) they wouldn't compile at all: func Add1024(type T integer)(s []T) {
for i, v := range s {
s[i] = v + 1024 // INVALID: 1024 not permitted by int8/uint8
}
} Nonetheless, unanticipated overflow is a problem with something like a generic |
Is it a problem if that code would not compile when you try to instantiate it with |
One important question is: what does that compilation failure look like? One of the major problems with C++ templates is the long nested compilation errors that result from using a template incorrectly. That is not something we want in Go. |
The compiler should know that it is dealing with a concrete instantiation of a generic type, so I would think that it could provide a suitably specific error message. Also, I would guess that the majority of generic code would use the |
Just checking back in on this -- has this ever been discussed among the core team? Is it DOA or might there still be a chance? I still think it represents an opportunity to do something truly Go-level innovative, simple, and elegant (with commensurate limits), but if a more conventional, general-purpose approach is favored, then that probably makes sense too. Anyway, would be great to hear any more specific comments if available. |
I just re-read this issue, and I have to say that I do not find it to be simple. Adding new categories like That said, defining new compile-time-type-safe data structures remains my major concern. As far as I can tell, the idea here is that a An 80% solution should introduce a minimum of new concepts to the language. For that matter, the same is true for a 100% solution. I don't see that this proposal meets that goal. |
Simple is all relative I guess. The definition I was using is that no new syntax is added, and the resulting code looks exactly like current Go code. I think people would find the generic code to be highly readable and "simple" to understand, per the examples above. There have been a number of objections to the draft design about the new syntax with all the extra parens etc being a major barrier. E.g., Dave Cheney's blog: https://dave.cheney.net/tag/generics I personally find C++ template code nearly unreadable because of all the extra parameters, and there is solid cognitive science research that says that people have a very limited ability to process multiple things at the same time, so adding additional type parameters just pushes the cognitive limits in a serious way (regardless if you use parens or <> or whatever). I really think this is a big issue and is the single most important advantage to this design. Per some discussion above, the proposal is that As for the objection about adding the new type categories, that is certainly valid. something has to be added to get the new functionality. I personally don't think that these would be difficult to understand, and given that these type categories are likely to be widely used under any proposal, people will end up having to learn these new categories one way or another. So in some ways just biting the bullet and adding simple, short, clear keywords to the language itself might be better than putting it off into a longer package name like Anyway, lots of judgment calls and again reasonable people will differ. But overall my feeling is that this represents the kind of simplicity argument that has driven Go decisions in the past, and has made the language so special -- the number one consideration has been to keep the code clean and easy to read and understand, and I see this as a way to achieve that goal in the realm of generics, whereas the draft proposal will introduce a lot of extra cognitive load, and is overall very similar to the way things have been done in other languages. Here's a chance to do something different! |
Adding When you point out that there are no type arguments at the call site, that leads me to wonder how for func AddTo(s []number, a number) {
for i := range s {
s[i] += a
}
} we can express the fact that |
For many cases, there is a convenient solution: // note: all args in same list (x,y) must be of same concrete type
func Min(x, y number) type(x) {
if x < y {
return x
}
return y
} If you don't want to enforce that constraint, then use separate type specifiers:
func AddTo(s []type(a), a number) {
for i := range s {
s[i] += a
}
} This is more readable I think than requiring explicit type args for everything, even though it is just a bit more complex and more indirect in terms of mental load than just writing
Anyway, there is certainly room for debate about option 2 but hopefully option 1 is reasonably satisfactory in any case. |
and would you call |
If func AddTo(s []type(a), a number) { The scoping here troubles me. Currently other than at package scope Go names are always scoped so that references must follow the definition. That changes here. |
I forgot about the func AddTo(s []number, a elem(s)) { In fact, it would probably be much more likely for this kind of code to appear as a method on a type rather than a standalone function like that. type NumSlice []number
func (s *NumSlice) AddTo(a elem(s)) { This would presumably be a fairly familiar pattern so seeing that As to whether the backward-order version should still be allowed, even if not encouraged, it is probably the case that the parser's multiple passes would be able to handle the forward reference within that same argument scope, so that would have to be a judgment / design call. |
and when I was referring to new syntax above, I was talking about something that would change the parse tree in a fundamental way, like adding a whole new set of type parameters to functions, as compared to just adding a new keyword that can be plugged in where e.g., previously you would have had |
I'm adding this to the overall intro, to highlight the key difference between this proposal and the draft proposal and other standard approaches to generics using separate type arguments: The draft proposal et al split the type information into two separate parts, while this proposal keeps the type specification unitary and in one place (where it normally is for non-generic code). For example, in the draft proposal: func Print2(type T1, T2)(s1 []T1, s2 []T2) { ... } You have to go back and forth between the type args and the regular args to understand what the types of func Print2(s1 slice, s2 slice) { ... } the type is fully specified (albeit still generic) in one place. To use a colorful metaphor, the draft design is like a horcrux that splits key information painfully across multiple places, whereas GNT's preserve the "natural" unity of type specification: you don't have to go searching across multiple hiding locations to find the type :) |
link added to first issue description (intro): https://en.wikipedia.org/wiki/Split_attention_effect |
Closing this in favor of the much simpler #39669 which is essentially a syntactic variant of the current draft proposal. |
This proposal is to add generic native types (GNTs) to Go: generic versions of each of the native builtin types (e.g.,
map
= generic map,slice
= generic slice,number
= generic number,float
= generic float,signed
= generic signed integer,unsigned
= generic unsigned integer, etc).Edit: Can also use generic types to specify container types, e.g.,
[]number
is a slice with number elements,map[string]number
, etc.GNTs support a substantial proportion of generic programming functionality, without adding any new syntax to the language: generic code looks identical to regular Go code, except for the use of these generic type names, and a few extra functions that access the type parameters of container objects such as maps and slices (e.g.,
elem(x)
is the type of the elment in a slice or map;key(m)
is the type of the key of a map;field(s, fieldName)
is the type of the given named field in astruct
;return(f)
is the type of return value from function, andtype(x)
is the type of a generic var, e.g., for use in return signature).The generic
struct
is the most challenging case, because of its unlimited number of type parameters. The proposed strategy is to adopt theinterface
concept, but specialized for thestruct
type, as astruct interface
-- see #23796 for discussion of a related proposal, where most of the objections were about "polluting" the existinginterface
concept with struct-specific functionality -- this problem is avoided by having a special type of interface only for structs, which provides all the benefits from that proposal, as well as supporting the definition of a generic struct type.Edit: It might be clearer to use
prototype
instead ofstruct interface
due to the differences between this type and the existinginterface
-- they do share some properties but also differ significantly.Here are some examples of some of the main generics use-cases under this proposal:
Edit: or prototype version:
In summary, GNTs leverage the "contracts" associated with the existing native types in the language, instead of introducing an entirely new syntax to specify novel such contracts. This makes programming with these types immediately intuitive and natural for any Go programmer, and the code as shown in the above examples inherits the simplicity and elegance of the existing Go syntax, as compared to other generics proposals that require additional type parameters etc.
Edit: The key difference between GNTs and the draft proposal (and other similar approaches using separate type parameters) is that these other approaches split the type information into two separate parts, while GNTs keep the type specification unitary and in one place (where it normally is for non-generic code). For example, in the draft proposal:
You have to go back and forth between the type args and the regular args to understand what the types of
s1
ands2
are -- the information is split across these two places. In contrast, under the GNT proposal:the type is fully specified (albeit still generic) in one place.
To use a colorful metaphor, the draft design is like a horcrux that splits key information painfully across multiple places, whereas GNT's preserve the "natural" unity of type specification: you don't have to go searching across multiple hiding locations to find the type :) More scientifically, reducing cognitive load by not having to integrate across these separate pieces of information is a well-established principle: https://en.wikipedia.org/wiki/Split_attention_effect
The major limitation is that generic functionality is limited to these existing native types. You cannot define
Min
/Max
functions that work across all native numbers and on non-native numbers such asbig.Int
. The bet here is that GNTs solve 80% or more of the use-cases in the cleanest, simplest way -- i.e., the defining feature of Go.Several of the required keywords are repurposed from existing ones, and thus would have no compatibility impact:
map
,chan
,interface
,struct
,struct interface
(combination)type(x)
,return(f)
(with optional 2nd arg specifying which return val if multiple -- could be index or name if named)These new ones would create potential conflicts:
slice
,array
,number
,unsigned
,signed
,float
,complex
,prototype
elem(x)
,key(x)
,field(x, fieldName)
See GNTs gist for a full discussion of the proposal -- would be happy to write a design doc according to standard template if requested.
The text was updated successfully, but these errors were encountered: