Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #254 Replace value in list

Replace all exact occurrences of "foo" with "bar" in the string list x

for i, v := range x {
	if v == "foo" {
		x[i] = "bar"
	}
}
func replaceAll[T comparable](s []T, old, new T) {
	for i, v := range s {
		if v == old {
			s[i] = new
		}
	}
}

replaceAll(x, "foo", "bar")

The type parameter T has a constraint: it must be comparable with ==
(replace {"foo" "bar"} x)

New implementation...