Copy string array (not reference) to map

I’m trying to come up with a way to sort HTML table data into some sort or array or map so that I can do something along with lines of:

package main

import “fmt”

func main() {
rows := make(map[string][]string)
row := []string{“this”,“is”,“a”,“row”}
rows[“test”] = row[:]
row = row[:0]
row = append(row,“another”)
row = append(row,“test”)
row = append(row,“of”)
row = append(row,“rows”)
rows[“another”] = row[:]

The problem is that it appears to be copying a reference to row rather then the values so when I run this I end up getting:

map[another:[another test of rows] test:[another test of rows]]

How do I copy the actual contents?



That’s because slices have the same underlying array. You may use copy to create a new one, e.g.:

rows["test"] = make([]string, 4)
copy(rows["test"], row[:])

Try it at the playground:


And you don’t really need to use row[:] it just means all of the slice. You can use just row. Like this


Thanks to both of you. That helped a lot.


1 Like

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