简体   繁体   中英

What does ` do in golang

I have a variable defined like this

var selectStatement = `
    SELECT role FROM abc INNER JOIN xyz ON (abc.name = 'Service list')
`

Now what I want to do is instead of using hardcoded 'Service list' I want to read a variable value something like

var myvar = "operation"
var selectStatement = `
    SELECT role FROM abc INNER JOIN xyz ON (abc.name = $myvar)
`

I know its very simple if there was "string" instead of `string` . How can I achieve this. What is the difference between "string" and `string` ?

` That back tick, (on the tilde key) is for declaring string literals. It makes it so you can have quotes and new lines and they are interpreted literally rather than breaking the string.

To solve your bigger problem use fmt.Sprintf so...

var selectStatement = `
    SELECT role FROM abc INNER JOIN xyz ON (abc.name = '%s')
`

selectStatement = fmt.Sprintf(selectStatement, ValueGoingWherePercentSIsNow)

This question is actually two questions: one in a topic and one in a body of the question.

What does ` do in GoLang

`string` is a raw string literal. In a raw string literal (within the quotes) any character may appear except backquote. A raw string literal is uninterpreted (implicitly UTF-8-encoded) characters. It means that backslashes have no special meaning and the string may contain newlines.

"string" is an interpreted string literal. With interpreted string literal backslash escapes interpreted as they are in rune literals. It can't contain newlines, although the escape sequence \\n is interpreted as a newline.

String interpolation

It is possible to do with fmt.Sprintf

func main(){
    myvar := "operation"
    selectStatement := `
        SELECT role FROM abc INNER JOIN xyz ON (abc.name = %s)
    `
    interpolated := fmt.Sprintf(selectStatement, myvar)
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM