golang:给定字符串,输出等效的golang字符串文字

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 (
    "repr"
)

// 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("a")
    println(repr.StrLit("a"))
    println(repr.StrLit(repr.StrLit("a")))
    println(repr.StrLit("This is a
test!"))
    println(repr.StrLit("As is\x00this!"))
}

This program when invoked should output the following:

"Hello World!"
a
"a"
"\"a\""
"This is a
test!"
"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 (
    "repr"
)

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

func main() {
    var a int = 5
    println(repr.StrLit(a))
    var c complex128 = 1.0+1.0i
    println(repr.StrLit(c))
}

This program should output:

5
1.0+1.0i

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!

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.