4 ms·
So does it have closures?
by SeanLuke 17y ago
So does it have closures?
- btilly 17y agoYes it does. It has full first class functions and closures. However the lack of generics means that you can't write a general-purpose map, filter, reduce, etc. You'll need to keep writing almost identical pieces of code. See http://golang.org/doc/go_spec.html#Function_literals http://golang.org/doc/go_spec.html#Function_literals for confirmation and http://groups.google.com/group/golang-nuts/browse_thread/thread/74a37a9923cdf327 http://groups.google.com/group/golang-nuts/browse_thread/thr... for more details.
- andreyf 17y agoHowever the lack of generics means that you can't write a general-purpose map, filter, reduce, etc. I'm not so sure, why not just define them "dynamically"? From the article: it's defined as an empty interface, and everything implements the empty interface
- scott_s 17y agoThat might be possible, but that seems to go against the design goal of making a systems programming language that can replace C.
- mbreese 17y agoOr have an interface "mappable" or "filterable", and then have everything include those methods... It's possible, but it does add a bit of extra complexity.
- btilly 17y agoWell if you follow the second link you will find Adam Langley (one of the initial developers of Go) saying that the type system precludes a generic map, grep, etc. You point out that everything implements the empty interface, but knowing that something implements the empty interface isn't very useful. A map, grep, etc needs to be passed a function and a bunch of data, then needs to apply the function to each piece of data. But the type system can't let you pass a piece of data to the function unless it knows the types are compatible. So if your function takes ints and adds them, then you really need to know that all of your pieces of data are ints. To use functions that accept data of other types, you will need a different version of grep for every type of function you accept. This is exactly the problem that generics tries to solve.
- jganetsk 17y agoHow do closures work in a language that has pass-by-value semantics? Does it copy all the closed-over data into the closure itself? Is the closure itself always heap-allocated and pass-by-reference, or is it pass-by-value?
- btilly 17y agoI'm not sure why you think there is a problem to be solved. When you execute some code you bind an environment to that code. (This binding step is necessary if you want recursion to work.) In the case of a closure you just leave the environment bound to the function that returns. It is irrelevant how data got into the environment - as long as it is there and remains bound to that scope, the closure will work. To be able to do this the environment needs to exist on the heap. However when you add the concurrency semantics that Go has, allocating things on the heap makes a ton of sense in general.