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.

About me

I’m Markus, a professional software consultant and developer. 🤓✨ You can reach me at [email protected].

I'm currently building Go courses over at golang.dk.