bkim::Blog

A Go quine

I just implemented my very first, ground-up quine in Go.

package main

import (
	"fmt"
)

const (
	before = `package main

import (
	"fmt"
)`
	this = `%[2]s

const (
	before = %[1]c%[2]s%[1]c
	this = %[1]c%[3]s%[1]c
	after = %[1]c%[4]s%[1]c
)

%[4]s`
	after = `func main() {
	fmt.Printf(this, '\x60', before, this, after)
}`
)

func main() {
	fmt.Printf(this, '\x60', before, this, after)
}

You can execute it yourself at https://play.golang.org/p/satPtYw8V7.

I got to say that I find it very readable. The tricks are

Now rereading this, I noticed that passing backtick as an argument is not necessary, and may be escaped directly into this as the ASCII code. Still, it feels more elegant to have those const declarations enveloped like %[1]c%[2]s%[1]c than \x60%[2]s\x60

Published in .