go - 如何在 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"}
解决方案
在 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)
例如,要转化[]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: conversion。
推荐阅读
- r - Remove Nested LOOP
- swift - Get the same PATH environment variable from a terminal command when debugging an app from Xcode?
- javascript - D3.js v5 - Update nodes from another array of nodes
- javascript - Vue JS 计算属性和 jquery
- c# - How to use Siteseeker with EPiServer post version 9?
- python - 如何避免用户在 django 中注册已使用的电子邮件?
- shell - 如何下载通过 Curl 命令从 GET api 响应收到的文件(*.txt 或 *.pdf)?
- python - How can I check if the event queue is finished for the on_pick event of matplotlib?
- java - java_home is not set and no 'java' command could be found in your path error while developloing react native app for andriod in windows
- meteor - Meteor.setInterval breaking after +1 day of uptime (callback: undefined)