简体   繁体   中英

Collections in golang

I am using golang as my server language (because I like learning new languages). As opposed to Python or Javascript, I like the fact that go is strongly typed.

I am looking for a design pattern to allow me to create collections for custom objects. In Java, C#, or C++, I would use generics. In C, I would hack the pre-processor. In golang, I was not able to come up with a solution.

I could always use interface{}, but then I would loose the advantages of strong typing. (Hello python/node.js runtime errors!)

Currently I am just copy-pasting my collections for every new type that I need, but I find myself struggling to maintain the code base, as now have ~10 copies of each collection. So I'm looking for a better design pattern. (Also, every ounce of my being is telling me that this is a bad idea)

I am not looking for a rant on how "there's no generics in go". I'm looking for actual experienced golang devs who have encountered and designed around such issues.

Unfortunately, if standard go data types like slices/maps don't have the features you need currently there is not much what can be done.

What would make implementing collections easier, is adding generics to go. As for right now, there is a draft and second version of the tools. You can find more information here .

https://github.com/ReactiveGo/jig is a tool that for should make your life easier by generating the collections you need.

Now that go supports generics, I took a shot at porting my old generics-base java collection framework to go (significantly gopherizing it in the process). The framework defines a nice set of simple interfaces and the collection types supported include:

  • Queues[T any] (wrap channels in a way that allows snapshots of the queued items)
  • Stacks[T any]
  • Sets[T any] (items are ordered and unique)
  • Lists[T any] (wrap arrays/slices behind common collection interfaces)
  • Catalogs[K any, V any] (wrap maps in a way that preserves the order of mapped values)

Also included in the framework are some agents that operate on the collection types:

  • Iterator[T any]
  • Formatter (formats any collection into a canonical string that can later be parsed)
  • Parser (parses the canonical string format for a collection into an instance of that collection)

You can check it out here: https://github.com/craterdog/go-frameworks/wiki/Collections

Note that this framework is still in an experimental state but any feedback and suggestions are welcome.

You could try to check this project: https://github.com/jose78/go-collection . This project provides a lot of methods to work easily with collections.

Regards, JC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM