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[:]
fmt.Println(rows)
}

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?

Thanks,

Rob

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: https://play.golang.org/p/Ppgv6_t88PJ

2 Likes

And you don’t really need to use row[:] it just means all of the slice. You can use just row. Like this https://play.golang.org/p/4RSRzEH1h71

3 Likes

Thanks to both of you. That helped a lot.

Rob

1 Like

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