On Sep 11, 2018, at 3:02 PM, Ian Lance Taylor <i...@golang.org> wrote: > > I'll just note briefly that I tossed field accessors in the contracts > design draft because it was easy, not because I thought it was an > important feature. It would be interesting to see a real use case for > it. At this point I would certainly be fine omitting any way to > specify field accessors.
You can always use getter/setter functions instead of field names in a generic function but it can get unwieldy and slow. Suppose you want to search in a tree by name. A generic function may look like this: //leaving out how the type parameter T is specified func SearchByName(t *T, n string) *T { if t == nil || t.name == n { return t } it t.left != nil && n < t.name { return SearchByName(t.left, n) } return SearchByName(t.right, n) } Any type containing the three named fields can be used here. An obvious alternative is be to pass a compare function to a generic tree search function as well as accessors for left and right subtrees. But directly using left and right fields seems clearer (and you don't need every type to implement these accessors -- this is already implicitly done by the fact that a type has named fields; why have a programmer duplicate the work). Another alternative is for a data structure to *embed* a tree node and all these functions are then defined on the tree node. But then the compare function can get screwy - it has to accept a ptr to a tree node and not the real data structure. ====== One way of looking at this is to say that for certain generic algorithms the parameter type has to have a specific structure, which can be a map or a slice or a tuple with certain named or structured components. IMHO even if we can not think of specific examples, exceptions should not be made unless there absolutely necessary. Exceptions are opposite of genericity. The key idea for generic algorithms is to specify only the *essential* details (or properties) and abstract away any inessential details. The "contract" construct seems to be a way of specifying these essential details. But I too think contracts do this "by example" and in a rather roundabout way. I think there may be a way out but need to think about it some more before talking about it. And I would much prefer "contract" to imply stronger guarantees, something associated with correctness! -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.