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
In js this is simply:
bot := DigitalAssistant{`${input}`, "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
In go, there is no such thing as string template literals like on es6. But you can definitely do something similar using fmt.Sprintf.
fmt.Sprintf("hello %s! happy coding.", input)
In your case it would be something like this:
bot := DigitalAssistant{fmt.Sprintf("%s", input), "teamAwesome", "awesomebotimagename", "0.1.0", 1, 8000, "health", "fakeperson@gmail.com"}
A curious question by the way. Why tho you need to use string template literals on a very straightforward string like ${input}
? why not just input
?
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"}
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
, it requires more than one step.
// 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 to take a look at go spec: conversion.