Using dot imports in views in Go

Written 18th of November 2020

I listened to an episode of the GoTimeFM podcast recently, about what the panelists would remove from the Go language, if it were possible if not for the Go version 1 backwards compatibility guarantee.

One of the things discussed is dot imports. In Go, this is the practice of importing a package into your local namespace, so you don't have to prefix exported functions, variables etc. with the package name, like so:

package main

import (
	. "fmt"
)

func main() {
	Println("Like magic! But beware.")
}

This practice is generally frowned upon, because it makes your code less explicit and thus less readable. As pointed out on Reddit by user SYS9000, it can also make your code more fragile, because the compilation of your file can break by adding an identifier to the imported package, which can lead to a name conflict.

However and ironically, the episode got me thinking about a nice use case for dot imports: when using the gomponents view library I'm building, it would be pretty neat to write your view components like this:

import (
	. "github.com/maragudk/gomponents"
	. "github.com/maragudk/gomponents/el"
)

func MyComponent() Node {
	return Div(
		H1("Hey!"),
		P(Text("Dot imports may make sense in this context."))
	)
}

Turns out this really makes building HTML components in Go much more readable, in my humble opinion, and is really close to writing plain HTML. All while keeping the good parts of writing components in Go: easy reusability, dynamic behaviour, type safety, etc. The only thing you probably have to do is have all your view components in a separate package (to prevent import name clashes), which is easily accomplished and probably a good idea anyway.

Unfortunately, because there are clashes between element and attribute names in HTML (for example, form, title, style), this won't work when importing both the el and attr packages from gomponents. I'll have to think about that one.

This is still an experiment, but I quite like it so far, and takes me one step further to writing server-side views as easily as possible.

What do you think? Let me know in the comments, or on Twitter at @markusrgw. There's also a Reddit thread.

About me

A picture of Markus.

I'm Markus, a professional software consultant and developer. 🤓✨ You can reach me on markus@maragu.dk or at @markusrgw. If you like my work, consider sponsoring me. You could also check out my LinkedIn profile, or do neither of these things and just grab a coffee and a biscuit.

Comments

Avatar of Pierre

Pierre
The nice to have go feature would be fonction imports like in python : from myres.com/mypackage.git/mylib import H1

Add comment

Newsletter

Is what I write useful to you? Sign up to my newsletter for software and business insights directly in your inbox. 😄 You could also use plain old RSS.