Reputation: 9873
I am trying to submit an email with multiple paramaters and I have emails in a separate file with some printing verbs, but since there are so many verbs I end up with a line like this:
message := fmt.Sprintf(util.CONTACT_EMAIL, form.Name, form.Email, form.Email, form.Phone, form.Phone, form.Message, ...)
and it just goes on and on which looks bad. And the reason I repeat some verbs is to get the href's, for example <a href"mailto:%s">%s</a>
, and so forth. If anyone has a better approach to that I'd really like to know.
But on to my question.. Does Go have a formatter that works similar to vsprintf in PHP? It basically takes an array as the arguments so it would be like:
string vsprintf(string $format , array $args)
..instead of the mess I have above, which allows it to be a bit more readable.
I looked on the docs but don't seem to see anything..but a lot of what Go does is still foreign to me so maybe I overlooked it.
Upvotes: 0
Views: 50
Reputation: 14539
If you just want to pass a slice of arguments to fmt.Sprintf
(or any other function that takes a variadic number of arguments) you can do that like this:
func main() {
s := []interface{}{1,2,5}
z := fmt.Sprintf("%d, %d, %d", s...)
print(z)
}
or if you have a slice of anything that isn't the empty interface, we have to copy it into a slice of the empty interface:
func main() {
s := []int{1,2,5}
// we need to copy each element one-by-one into a []interface{}
// because they are laid out differently in memory in go.
var x []interface{}
for _, i := range s {
x = append(x, i)
}
// pass the contents of the new slice into sprintf
z := fmt.Sprintf("%d, %d, %d", x...)
print(z)
}
Upvotes: 1