Take the 2-minute tour ×

Writing go applications which output valid go code is probably best done using the built-in "go" package and some of its sub-packages ("go/ast", "go/token", "go/printer", etc).

To create a string-literal expression, you need to create an ast.BasicLit:

l := &ast.BasicLit{Kind: token.STRING, Value: "\"Hello world!\""}

In my go program, I've got a string and I need to create an ast.BasicLit which when output will produce a string literal which faithfully reproduces the same string. In order to do that, I must derive from the string a string which represents the go-syntax literal which represents the string. (This concept is so meta, it's difficult to describe without ambiguity.)

What I'm looking for in go is basically the equivalent of the Python built-in repr(). It's an operation which you might call the "opposite" of what eval() in JavaScript does.

An example should help illustrate what I'm looking for.

package main

import (

// Assume the operation I'm hoping to find is implemented in the package "repr" as a function called "StrLit()" with the signature "func(v string) string".

func main() {
    println(repr.StrLit("Hello World!"))
    println(repr.StrLit("This is a\ntest!"))
    println(repr.StrLit("As is\x00this!"))

This program when invoked should output the following:

"Hello World!"
"This is a\ntest!"
"As is\x00this!"

While my specific issue regards strings, I'd be interested in a general solution which would work on values of any type (integer types, float types, even complex types) as follows:

package main

import (

// Assume this time that repr.StrLit() has the signature "func(v interface{}) string".

func main() {
    var a int = 5
    var c complex128 = 1.0+1.0i

This program should output:


I've looked quite a bit through the standard library documentation but haven't really found anything which looks close to what I'm looking for. Hopefully you folks can help me.

Thanks in advance!

share|improve this question

1 Answer 1

up vote 3 down vote accepted

You want http://golang.org/pkg/fmt/#Sprintf with the %#v formatter.

lit := fmt.Sprintf("%#v", "foo") will print out "foo"

See: http://play.golang.org/p/nFAKFObXE5 for an example with various different types including complex literals like structs.

The fmt package has a lot of useful format verbs so be sure to check out the rundown in it's docs.

share|improve this answer
Perfect! Exactly what I'm looking for! Thanks much! –  AntiMS Jul 22 '13 at 13:01

Your Answer


