Hacker News new | ask | show | jobs
by nu11ptr 1095 days ago
This is a great example of why I dislike Go. It is not obvious that a slice is passed by value while a map is not or why. Therefore every action on it feels a bit weird because of that, and now you have functions like "clear" that take a very non-obvious action. Personally, I'd rather have pass-by-value return an error and only allow pass-by-reference (better: they should have had maps and slices be pointers). I'm not sure I'd ever use a function that set every value to its zero type.
2 comments

I agree the semantics seem weird, I've occasionally wanted the equivalent of x = clear(x) but I can't think of a time when I've wanted to set all the values to the zero value.

The bug doesn't seem to discuss use cases for it either. The most I could find is: https://github.com/golang/go/issues/56351#issuecomment-13326...

Which boils down to "doing what clear(slice) does cannot be implemented efficiently today" but I'm not sure how having an efficient way to do something folks don't want is useful?

There's already a memory clearing optimization in the compiler: https://github.com/golang/go/issues/19266

So yeah I'm not sure under what situations folks will use clear(slice).

You often do it in Go to avoid pointing at something needlessly which would delay or even keep that something from being garbage collected.