Go中的字符串文字中的变量捕获?

时间:2014-01-22 00:54:05

标签: syntax go string-interpolation

在Ruby中,我可以直接捕获字符串文字中的变量,如bash

SRCDIR  =   "aaa"
DSTDIR  =   "bbb"

puts "SRCDIR = #{SRCDIR}"
puts "DSTDIR = #{DSTDIR}"

这是一个简单而微小的功能,但非常好,让它感觉像一个shell脚本。如果我必须编写一个复杂的shell脚本,这会有很大帮助,因为这样就不需要替换,连接和格式表达。

Go有这样的东西吗?如果是的话,如何使用它?

4 个答案:

答案 0 :(得分:2)

不是没有格式化字符串;通常的方法是使用fmt.Printffmt.Sprintf

srcdir := "aaa"
dstdir := "bbb"

// separated out Sprintf and Println for clarity
fmt.Println(fmt.Sprintf("SRCDIR = %s", srcdir))
fmt.Println(fmt.Sprintf("DSTDIR = %s", dstdir))

// could be shortened if you're just printing them
fmt.Printf("SRCDIR = %s\n", srcdir)
fmt.Printf("DSTDIR = %s\n", dstdir)

答案 1 :(得分:0)

Wes说的话。我应该补充一点,如果你使用的是自定义类型,你可以定义一个方法,它上面有一个签名String() string(基本上使它们满足fmt.Stringer接口),然后直接传递这些类型的实例到期望字符串的fmt包的函数,例如fmt.Println()。可以在"Effective Go"中找到对此的简单介绍。

答案 2 :(得分:0)

您必须像JS中那样使用+运算符

main.go

package main

import "fmt"

func main() {

    movieQuote := `"What's the most you ever lost on a coin toss?"`
    statement := `Back-ticks allow double quotes, ` + movieQuote + `, and single quote apostrophe's`

    fmt.Println("movieQuote: ", movieQuote)
    fmt.Println("statement: ", statement)
}

运行

go run main.go

输出:

movieQuote:  "What's the most you ever lost on a coin toss?"
statement:  Back-ticks allow double quotes, "What's the most you ever lost on a coin toss?", and single quote apostrophe's

答案 3 :(得分:0)

GQL查询

package main

import (
    "github.com/gookit/color"
)

const (
    offerInfo string = `{
        id
        name
        description
        logoURL
        opt_ins {
          id
          name
          description
        }
      }`
)

func QueryAllOffers() string {
    return `{ offer ` + offerInfo + `}`
}

func QueryOfferByID(id string) string {
    return `{
        offer (id: "` + string(id)  + `")` + offerInfo + ` }`
}

func main() {
    queryAllOffers := QueryAllOffers()
    color.Cyan.Println(queryAllOffers)

    offerID := "0001"
    queryOfferByID := QueryOfferByID(offerID)
    color.Blue.Println(queryOfferByID)
}

输出:queryAllOffers

{
  offer {
    id
    name
    description
    logoURL
    opt_ins {
      id
      name
      description
    }
  }
}

输出:queryOfferById

{
  offer(id: "0001") {
    id
    name
    description
    logoURL
    opt_ins {
      id
      name
      description
    }
  }
}