如何在GO中使用字符串文字



在GO模板中,我想用变量替换下面的字符串:

bot := DigitalAssistant{"bobisyouruncle", "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}

说我想用变量input

替换bobisyouruncle

我该怎么做?

在JS中,这简直就是:

bot := DigitalAssistant{`${input}`, "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}

在GO中,没有字符串模板文字(例如ES6上(。但是,您绝对可以使用fmt.sprintf。

做类似的事情
fmt.Sprintf("hello %s! happy coding.", input)

在您的情况下是:

bot := DigitalAssistant{
    fmt.Sprintf("%s", input),
    "teamAwesome",
    "awesomebotimagename",
    "0.1.0",
    1,
    8000,
    "health",
    "fakeperson@gmail.com",
}

顺便说一句,

一个好奇的问题。为什么需要在像${input}这样的非常简单的字符串上使用字符串模板文字?为什么不只是input


编辑1

我不能仅仅输入,因为GO给出错误无法将输入(键入[]字节(用作字段值中的字符串

中的字符串

[]byte可转换为字符串。如果您的input类型为[]byte,只需将其写入string(input)

bot := DigitalAssistant{
    string(input),
    "teamAwesome",
    "awesomebotimagename",
    "0.1.0",
    1,
    8000,
    "health",
    "fakeperson@gmail.com",
}

编辑2

如果值是int,为什么我不能这样做?因此,对于括号1和8000中的值,我不能只做int(numberinput)int(portinput),否则我将获得错误cannot use numberinput (type []byte) as the type int in field value

可以通过使用显式转换T(v)来从string转换为[]byte,反之亦然。但是,此方法并不适用于所有类型。

例如,要将[]byte转换为int需要更多的努力。

// convert `[]byte` into `string` using explicit conversion
valueInString := string(bytesData) 
// then use `strconv.Atoi()` to convert `string` into `int`
valueInInteger, _ := strconv.Atoi(valueInString) 
fmt.Println(valueInInteger)

我建议看看GO Spec:转换。

相关内容

最新更新