Access slice element and change its value

How to change the value of a slice element using a variable as index.

In pure go:

// Replace "Italy" by "Belgium" - 
	myindex := 2
	countries := []string{"France", "Germany", "Italy"}
	countries[myindex] = "Belgium"

How to to the same in Go template/Hugo speek? The following attempt throws an error.

{{ $myindex := 2 }}
{{ $countries := slice "France" "Germany" "Italy" }}
{{ index $countries $myindex = "Belgium"}}

According to the doc, the index func only returns a value, that’s why Hugo throws:
unexpected "=" in operand

It’s verbose. But I don’t know of a better way.

{{ $countries := slice "France" "Germany" "Italy" }}
{{ $countries }}
<!-- [France Germany Italy] -->

{{ $newCountries := slice }}
{{ $newCountries }}
<!-- [] -->

{{ $myindex := 2 }}

{{ range $index, $value := $countries }}
  {{ $newValue := $value }}
  {{ if eq $index $myindex}}
    {{ $newValue = "Belgium" }}
  {{ end }}
  {{ $newCountries = $newCountries | append $newValue }}
{{ end }}

{{ $newCountries }}
<!-- [France Germany Belgium] -->
2 Likes

You could try symdiff, but the ordering would not be maintained.

{{ $countries := slice "France" "Germany" "Italy" }}
{{ $countries | symdiff (slice "Germany" "Belgium" }}

Or you could use a dict instead, but you would need to have keys and values. It would allow you to maintain ordering if important.

{{ $countries := dict "1" "Germany" "2" "France" "3" "Italy" }}
{{ $change := dict "2" "Belgium" }}
{{ $newCountries := merge $countries $change }}
2 Likes

As ordering isn’t important, I will go the sympdiff way. Strange that a straight forward (read trivial) solution is not possible when the underlying language allows it. Thanks for pointing me in the right direction.

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