3 ms·
One thing made me gasp then laugh. Kelsey said “for the next step, you just have to put this in your Go imports, you don’t have to use it or anything: _ "g
by tptacek 6y ago
One thing made me gasp then laugh. Kelsey said “for the next step, you just have to put this in your Go imports, you don’t have to use it or anything:
_ "google.golang.org/xds"
I was all “WTF how can that do anything?” but then a few minutes later he started wiring endpoint URIs into config files that began with xdi: and oh, of course. Still, is there, a bit of a code smell happening or is that just me?
It's not a code smell; it's idiomatic Go; the search he wants is [import for side effects].
- gen220 6y agoTo be fair, you can write a lot of idiomatic code without ever using packages that use `init()` [0]. (The most common usage is importing database drivers). I've written Go for a while, and it still feels a bit exotic, compared to its other control flow patterns. Maybe "code smell" was the wrong word. But writing "surprising" logic in an `init()` function would definitely not be considered idiomatic. [0]: https://golang.org/doc/effective_go.html#init https://golang.org/doc/effective_go.html#init
- tptacek 6y agoI guess I'd just say, when a Go programmer sees an "import _" in the README.md for a library in Github, they generally know exactly what's happening; "oh, you import this for side effects".
- gen220 6y agoYea that's fair. It's admittedly a more exotic than the traditional alternative: importing a module, initializing some struct, passing it to some other module's struct-initialization. Of course, now that I write it all out, and I imagine that I'd need to write all that just to give my gRPC service a load balancer... ok, I can accept the fancy hand-waves, give me the underscore import! :)
- fragmede 6y agoPart of what makes this idiomatic in golang is that the compiler will refuse to compile code with unused imports floating around. It's a bit weird when importing for side effects (those imports are basically marked 'always in use'), but never having random unused imports after refactoring code is a code aroma, and enforced by the compiler. (I am not aware of tooling to handle the corner case of an import-for-side-effect library going unused after refactor.)
- xxpor 6y agoI also think there's a subtle joke here, check the top author of https://www.w3.org/TR/xml-names/ https://www.w3.org/TR/xml-names/ :)
- chrisbroadfoot 6y agoAlso, correction, the correct import is _ "google.golang.org/grpc/xds"
- apta 6y agoIt's quite bad design from golang to have these kind of imports. They claim they dislike "magic", yet here we are.