Default value for index in golang templates


I am trying to set a default value when a value is not found in an array using the {{index}} template function. My best attempt is to use the {{or}} function but it doesnt seem to work as expected. As far as I can tell it works for a map[string] but not for a map[string][]string. Why is this, and is there a better way.

map[string[]string is not valid syntax. What did you really mean?

Ok, have edited. I meant map[string][]string.

I think this is because the result of {{index}} on a []string, with an out of range index, is a blank string right? But if so, does that count as ‘empty’

Returns the boolean OR of its arguments by returning the
first non-empty argument or the last argument, that is,
“or x y” behaves as “if x then x else y”. All the
arguments are evaluated.

hmm {{or "" "default"}} works as expected though

fmt.Errorf does not print the errors that are happening (even though they were “not expected”). Here is a version using log.Printf that shows them:

Now I feel stupid!

But, what is the reason why it works for map but not a slice? Is there something I can do without resorting to custom functions?

Maps return the zero value for nil or missing entries. Slices have bounds checks.

Is there something I can do without resorting to custom functions?

Between variables, if, len, index, and or you could probably get something that works. If you need to use the same logic more than once, you will have to replicate that solution everywhere you need it.

Using a custom function gives you the opportunity to cleanly express your design intent and use an API that does exactly what you need in the way you need it done. Using one more than once is even better.


Thanks, I will go back to using custom function then. I was hoping to factor all my custom functions out by using the standard functions, but that probably would make the template too cumbersome as you suggest. Thanks again

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.