A use case for importing with blank identifier in golang

I was writing a program that resizes images. I wanted it to be able to recognize images in different formats like JPEG, PNG, GIF and convert them to JPEG.

So in addition to the image and image/jpeg packages, I also had to import image/png and image/gif only to register their respective decoders.

Had I not imported those, the scaler would only be able to read JPEG images.

package main

import(
  "image"
  "image/jpeg" // I wanted to export the images as JPEG
  _ "image/png"
  _ "image/gif"
)

// ...

The relevant documentation from the image package:

Decoding any particular image format requires the prior registration of a decoder function. Registration is typically automatic as a side effect of initializing that format's package so that, to decode a PNG image, it suffices to have:

import _ "image/png"

A use case is when what you want is only the init function doing some initialization (for example registering themselves so that you don't have to explictely call them).

An exemple is the registring of some database drivers :

import (
    "database/sql"
    _ "github.com/ziutek/mymysql/godrv"
)

This is because of the init function

each source file can define its own niladic init function to set up whatever state is required. (Actually each file can have multiple init functions.)

And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.

That is how the go-sqlite3 mentioned in "What does an underscore in front of an import statement mean in Go" works.

func init() {
    sql.Register("sqlite3", &SQLiteDriver{})
}

You have another example in "Understanding Golang Packagese":

In some contexts, we may need to import a package only for invoking it’s init method, where we don’t need to call forth other methods of the package.
If we imported a package and are not using the package identifier in the program, Go compiler will show an error.
In such a situation, we can use a blank identifier ( _ ) as the package alias name, so the compiler ignores the error of not using the package identifier, but will still invoke the init function.

Tags:

Go