DEV Community

Discussion on: Why I’m So Frustrated With Go

Collapse
 
nickgrim profile image
Nick Grimshaw • Edited

To solve the iterate-in-some-order-but-maintain-immutability problem, how about something like this:

type AnimalMap struct {
        mapping map[string]Animal
        order []string
}

func (am *AnimalMap) Range(f func(Animal)) {
        for _, s := range am.order {
                f(am.mapping[s])
        }
}
Enter fullscreen mode Exit fullscreen mode

...and then just:

printThem := func(a Animal) {
        fmt.Printf("%v\n", a)
}
m.Range(printThem)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
blixt profile image
Blixt • Edited

Why not make the map an index into a slice of Animal if you're already going for immutability? Simpler/faster to iterate.

type AnimalMap struct {
    index map[string]int
    items []Animal
}

(The key lookup would become am.items[am.index["value"]])

If you were going for mutability, it'd be simpler to make the index map[string]*Animal (which might not be a bad idea even with immutable access – of course the index matters more/less depending on how much you'd be inserting/deleting.).

Collapse
 
klnusbaum profile image
Kurtis Nusbaum

I hadn't thought about this. This is interesting.

That said, I think the boiler plate of always having to wrap my code in a closure is a little frustrating. The example provided here is not to bad, but I think I could envision code that's more complex and this being a little more frustrating to do. Not only that, but I have to wrap each new piece of iteration code with a closure.

What do you think?

Collapse
 
klnusbaum profile image
Kurtis Nusbaum

I thought about this a little more and I really like your solution. While it adds closure boiler plate at the call site, it also removes the need for the caller to write their own loop. So it's actually a wash in that sense. But it removes all the stuff I had to add for immutability. I actually really like this. My hats off to you.

That said, it's still 10 lines of code I have to write every time I want a data structure like this. Which is an order of magnitude larger than other languages.

Thread Thread
 
irongopher profile image
Darren Venables

/u/shovelpost commented this on reddit.

"TL;DR

  • "Author complains he has to write 30 extra lines of code in Go.
  • "Person in comments provides a solution that reduces code to 10 lines.
  • "Author complains he has to write 10 extra lines of code in Go."

You are a developer, and you must write some code. Go is not a language meant to be all things to all people. Look at C++, C#, and Java to see what happens to languages that walk that road: they become bloated with features, fast.

Thread Thread
 
chicocode profile image
Francisco Hisashi Berrocal • Edited

In Javascript you don't need 10 lines of code to accomplish the same results and is still a small core language.
You would use some lib to do that, maybe the problem with go is the immature ecosystem.