6 ms·
Maybe a Go programmer can enlighten me - without generics, how can you have data structures implementations that can contain more than one type? Do you have to
by whatshisface 8y ago
Maybe a Go programmer can enlighten me - without generics, how can you have data structures implementations that can contain more than one type? Do you have to have one linked list implementation for every type in your program? Do you have to abandon type checking by using an equivalent of void pointers? Or is the type system smart enough that you'd never need generics in the first place?
- nicoburns 8y agoMy understanding is that the standard library containers implement generics via special compuler magic, and everyone else is using `interface {}`, which is the equivalent of a void point or "any" type in Go.
- emersion 8y agoIt's not strictly speaking "standard library containers", but rather "builtin containers".
- zeveb 8y agoIt's really not the equivalent of a void pointer, because interface{} is still typed, and you can still interrogate its type, and the runtime prevents you from using it as any type other what it actually is. So it's far safer than a void pointer, although it can crash the program — but cleanly (because of the aforementioned runtime checks).
- emersion 8y agoYou'd have to use an equivalent of `void *` (for Go, it's the empty interface: `interface{}`). However in 99% of the cases the builtin slice and map data structures are enough.
- kkirsche 8y agoI believe this is done using protocols / interfaces where you declare a shared api of the objects
- pjmlp 8y agoThey make use of code generation like early MS-DOS C++ compilers, check Kubernetes source code.
- vbezhenar 8y agoTime for Go++?
- pjmlp 8y agoNot at all, generics like CLU (1975) does, would already be better than the current state. http://www.pmg.lcs.mit.edu/CLU.html http://www.pmg.lcs.mit.edu/CLU.html
- atilaneves 8y agoIf I had the time, I'd love to apply the C to C++ diff on top of Go (templates, overloading, etc.), release it as Go++, and watch the world burn. Just for the lulz.
- Svip 8y agoYou generally try to design your list so it contains types with common methods by using an interface (not the any type interface{}, mind). You could have a list (slice or map) of io.Writer, where it can contain any type that implements Write([]byte) on itself.
- kasey_junk 8y agoFirst go does have generics. It just doesn’t have user defined generics. But to answer your question go has really mediocre support for a wide variety of problems. Some that burn me a lot is support for future/promises and support for modern lock free algorithms. So you end up either writing non-optimal replacements, losing type safety or in some case code generation is used.
- emersion 8y ago>Some that burn me a lot is support for future/promises This doesn't make sense in Go. Nothing is asynchronous in Go, everything is blocking. You use goroutines to execute multiple tasks at the same time. That's a big part of what makes Go simple: it's a lot easier to understand sequential code than spaghetti callbacks and promises (it's somewhat similar to async/await in the JavaScript world).
- kasey_junk 8y agoYet open up nearly any large golang codebase and you’ll find a channel being used to return a single answer response in the future.
- emersion 8y agoWhat's wrong with that? Go has channels thus it doesn't need futures/promises.
- kasey_junk 8y agoSome problems are more simply modeled as futures/promises than csp. Go’s unsophisticated type system makes it difficult to write a good standard generic data structure library such as a future/promise library. That leads to people either writing a poor replacement, not using that style, or losing type safety. This is precisely what you would predict upon learning golang doesn’t have user defined genetics & ive had it bite me more than once in real projects.
- 8y ago
- dana321 8y agointerface{} is the equivalent of C++17's std::any, of which you can put anything including vector (slice) and maps. If you really want high performance with many different types of a function, its a case of copy-paste-modifying your code. Its a language that is straight-forward, its the antitheisis of tmtowtdi.
- j16sdiz 8y agoYou use an interface. Golang use duck typing. It is very flexible and very simple. (Some times too simple)
- kuschku 8y agoSo how do I make e.g. a TreeSet of something, put my elements in, and get them back out as the same type, without casting?
- jstimpfle 8y agoGo has a kind of generics that also maps cleanly to machine-level generics: interface{}, which is like void* in C. Whereas all the other kinds of generics, I believe, can't offer this quality. They require a lot of machine code instanciations (like C++'s template system). Or at least, in the case of virtual functions ("dynamic polymorphism" with VTables), they cause more brittle abstraction boundaries. Think how in C++, when definining a class, you need to expose a lot of internal details in the header file -- list all the private member functions and fields, etc. This has lead to the so-called PIMPL idiom which is exactly what you do in Go or C.
- pjmlp 8y agoYou don't need to expose any internal details on other languages that make use of generics. Even on C++ this is be eventually a thing of the past, after modules get finally adopted. Using how C++ currently does as argument against generics is a pretty weak argument, given the various ways to implemente them since CLU and ML introduced generic programming into the world.
- jstimpfle 8y agoLayouts of separately compiled classes/structs must still be exposed to the compiler. You can't hide layouts away, they are part of the interface. With all the disadvantages that dependencies bring. > Using how C++ currently does as argument against generics is a pretty weak argument, given the various ways to implemente them since CLU and ML introduced generic programming into the world. I would be interested to know how you think the problem of tighter coupling (a.k.a dependencies) is solveable, because I don't see a solution. For example, I'm pretty sure that typeclasses in Haskell are implemented with either of those two approaches I've mentioned depending on the situation. (Maybe it's possible if we require more information for the linker? I haven't thought through this.)
- pjmlp 8y agoExposed to the compiler doesn't imply exposed to everyone else to see. It is solvable by not sitting in an ivory tower using C++ and Java as the typical examples why Go won't get generics, and instead engage with generics friendly communities.
- weberc2 8y agoYeah, you have to either give up type safety (Go's "void pointers" retain runtime type information, so it's closer to a Python object than a void pointer) or you have to write each implementation. In the case of linked list, that's not a big deal: `type List struct { Next *List; Value int}` and Go comes with a handful of useful generic types (slices, arrays, maps, channels, etc). It also has interfaces and closures, so you can generally go a long way without generics. That said, there are still cases where generics would be useful; however, a lot of the people who complain about generics missing from Go tend to exaggerate the extent to which this is a problem, "You can't ship software in a language without generics!". In the case of Go, you have something like 97% type safe code compared to the many, many successful Python and JavaScript programs that ship with 0% type safety. And lastly, one thing that you can't really appreciate without trying Go--the lack of generics/expressiveness and general simplicity of the language largely means everyone writes the same boring, predictable code, which means you can pretty much pick up any project on GitHub or your own code from years ago and understand it almost immediately. This isn't to say that generics aren't worth it; only that the debate kind of sucks because one side is ignoring that rather significant point.
- latronic_notron 8y ago> "You can't ship software in a language without generics!" Isn't this is a strawman? Most arguments in favor of generics in this thread and elsewhere are well informed and people just want safer code... As you said, you can already have generics using unsafe solutions. Some built-in types have generics. Most people just want this type safety. interface{} does feel like a temporary and clunky solution for people used to generics. > And lastly, one thing that you can't really appreciate without trying Go--the lack of generics/expressiveness and general simplicity of the language largely means everyone writes the same boring, predictable code, which means you can pretty much pick up any project on GitHub or your own code from years ago and understand it almost immediately. I don't get this argument. Why are generics more complicated than other features? Has this hypothesis been tested? I personally find that using generics is way easier and faster than interface{}, Reflection or code generation. Also simpler and less error-prone than features from other languages like inheritance, operator overloading and unbounded coroutines.
- rebeccaskinner 8y agoInterfaces help a little bit. You can't really build re-usable data structures without falling back to `interface{}` and then incurring a performance hit from using reflection to get a well-typed value back out; but you can at least make your bespoke structures very marginally more reusable by defining interfaces ad-hoc.
- weberc2 8y agoTo be clear, you use cheap type assertions to get a well-typed value back out. You can use expensive operations from the `reflect` library to do other things, but not to get a well-typed value back out.
- rebeccaskinner 8y agoLooking at some benchmarks it does look like newer versions of Go at least have pretty reasonable performance for type assertions. That makes the situation a little less bad, but doesn't negate the general ugliness of having type assertions every time you want to get a value back out of a generic data structure.
- weberc2 8y agoFully agree; dealing with `interface{}` is generally pretty tedious.
- robmccoll 8y agoAs many others have stated, there are options. In the linked list example, you could use: - container/list.List which uses its own Element with internal pointers and interface{} for values - write a type-specific implementation (not generic, but no runtime type assertion) - write your own implementation using your own node / element interface type (maybe your list is generic to types that support io.Writer - generic for some use, but if you need access to specific types, you're back to runtime type assertions) - write your own interface{} implementation (constantly needs runtime type assertions) - use code generation (maintenance is harder, potentially non-standard tooling / build steps, but hey - no runtime type assertions) - use a slice instead of a list (Go's version of vectors / dynamic arrays) - still requires some implementation, but the language has a lot of built-ins that make this easier. Depends on use. If you are doing a lot of insertions in the middle, this may suck, FIFO may suck and you need to be careful about not doing append()-shift and effectively leaking memory, LIFO this is dynamic and gives you good cache locality. Up shot is no-runtime type stuff and at least the slices themselves and the built-ins are generic.