Mel*_*oni -1 go string-literals
在 go 模板中,我想用变量替换下面的字符串:
bot := DigitalAssistant{"bobisyouruncle", "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
Run Code Online (Sandbox Code Playgroud)
说我想bobisyouruncle用变量替换input
在 js 中,这很简单:
bot := DigitalAssistant{`${input}`, "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
Run Code Online (Sandbox Code Playgroud)
nov*_*ung 13
在 Go 中,没有像 es6 那样的字符串模板文字这样的东西。但是,您绝对可以使用fmt.Sprintf做类似的事情。
fmt.Sprintf("hello %s! happy coding.", input)
Run Code Online (Sandbox Code Playgroud)
在您的情况下,它将是:
bot := DigitalAssistant{fmt.Sprintf("%s", input), "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
Run Code Online (Sandbox Code Playgroud)
顺便问一个奇怪的问题。为什么需要在非常简单的字符串上使用字符串模板文字,例如${input}?为什么不只是input?
我不能只输入输入,因为 go 给出了错误不能使用输入(类型 [] 字节)作为字段值中的类型字符串
[]byte可以转换成字符串。如果您的input类型是[]byte,只需将其写为string(input).
bot := DigitalAssistant{string(input), "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
Run Code Online (Sandbox Code Playgroud)
如果值是 int,为什么我不能做同样的事情?因此,在括号内的值1和8000,我不能只是做
int(numberinput)或int(portinput)否则我会得到错误cannot use numberinput (type []byte) as the type int in field value
通过使用显式转换可以实现从stringto[]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)
Run Code Online (Sandbox Code Playgroud)
我建议看看go spec: conversion。
| 归档时间: |
|
| 查看次数: |
9044 次 |
| 最近记录: |