Issue
In a go template I want to replace the the strings below with variables:
bot := DigitalAssistant{"bobisyouruncle", "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
Say I want to replace bobisyouruncle
with the variable input
How can I do this?
In js this is simply:
bot := DigitalAssistant{`${input}`, "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
Solution
In Go, there is no such thing as string template literals such as on the es6. However, you can definitely do something similar by using fmt.Sprintf.
fmt.Sprintf("hello %s! happy coding.", input)
In your case it would be:
bot := DigitalAssistant{
fmt.Sprintf("%s", input),
"teamAwesome",
"awesomebotimagename",
"0.1.0",
1,
8000,
"health",
"fakeperson@gmail.com",
}
A curious question by the way. Why need to use string template literals on a very straightforward string like ${input}
? why not just input
?
EDIT 1
I cannot just put input because go gives the error cannot use input (type []byte) as type string in field value
[]byte
is convertible into string. If your input
type is []byte
, simply write it as string(input)
.
bot := DigitalAssistant{
string(input),
"teamAwesome",
"awesomebotimagename",
"0.1.0",
1,
8000,
"health",
"fakeperson@gmail.com",
}
EDIT 2
why can’t I do the same if the value is an int? So for the values in the brackets 1 and 8000 I can’t just do
int(numberinput)
orint(portinput)
or I’ll get the errorcannot use numberinput (type []byte) as the type int in field value
Conversion from string
to []byte
or vice versa can be achieved by using the explicit conversion T(v)
. However, this method is not applicable across all types.
For example, to convert []byte
into int
more effort is required.
// 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)
I suggest taking a look at go spec: conversion.
Answered By – novalagung
Answer Checked By – Candace Johnson (GoLangFix Volunteer)