Copy string array (not reference) to map

(Rob Marshall) #1

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?



(Ignacio Gómez) #2

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:

(Johan Dahl) #3

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

(Rob Marshall) #4

Thanks to both of you. That helped a lot.