首页 > 解决方案 > 如何在 go 中使用字符串文字

问题描述

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

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

说我想bobisyouruncle用变量替换input

我怎样才能做到这一点?

在 js 中,这很简单:

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

标签: gostring-literals

解决方案


在 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 给出了错误 cannot use input (type []byte) as type string in field value

[]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

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

例如,要转化[]byteint更多的努力是必需的。

// 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: conversion


推荐阅读