Robert A. Uhl

A quine in Go

This morning I thought ‘hey, I wonder how difficult it is to write a quine in Go.’ Spoiler alert: pretty easy.

What’s a quine? It is self-replicating program, i.e. a program whose output is itself. I knew what they were, but I had never actually sat down and tried to write one (I know, I know … it’s an elementary exercise, I just never got around to doing it before).

A quine in most languages needs to duplicate its source code: once as actual source, and once as a string to be output by that source, containing that source. But how can the string contain the source which contains itself which contains the source … ad infinitum? It’s actually really easy, with quoting.

To save myself the bother of hand-writing the quoted code, I wrote this to bootstrap it:

package main

import "fmt"

var template = `package main

import "fmt"

var template = %q

func main() {
        fmt.Printf(template, template)
}
`

func main() {
        fmt.Printf(template, template)
}

When run, this outputs the actual quine:

package main

import "fmt"

var template = "package main\n\nimport \"fmt\"\n\nvar template = %q\n\nfunc main() {\n\tfmt.Printf(template, template)\n}\n"

func main() {
      fmt.Printf(template, template)
}

The astute reader will notice one key difference here: my bootstrap uses `​` quoting, while the quine uses "" instead. The reason is that Go’s formatted output offers quoted output, which quotes everything correctly for one, including double-quotes themselves, but there is no way to include backticks inside of backticks.

As a result, the final quine is a little less readable.


Share