Skip to content

Instantly share code, notes, and snippets.

@kitlabcode
Created April 13, 2023 20:10
Show Gist options
  • Select an option

  • Save kitlabcode/319b230ec2fff14f1bb61437c622b611 to your computer and use it in GitHub Desktop.

Select an option

Save kitlabcode/319b230ec2fff14f1bb61437c622b611 to your computer and use it in GitHub Desktop.
copy slice and append - used to build permutations
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
type Item struct {
name string
number int
}
func (it *Item) copy() *Item {
return &Item{
name: it.name,
number: it.number,
}
}
func main() {
names := []string{"a", "b"}
numbers := []int{1, 2}
items := []*Item{}
for _, name := range names {
item := &Item{name: name}
items = append(items, item)
}
for n, i := range numbers {
if n > 0 {
fmt.Println(n, "make a copy of the items")
itemCopies := make([]*Item, len(items))
copy(itemCopies, items)
for j := 0; j < len(items); j++ {
itemCopies[j] = items[j].copy()
}
fmt.Println(n, "set the numbers on the copies")
for _, item := range itemCopies {
item.number = i
}
fmt.Println(n, "append the copies to the original")
items = append(items, itemCopies...)
} else {
fmt.Println(n, "first pass set all the items to the first number")
for _, item := range items {
item.number = i
}
}
}
for n, i := range items {
fmt.Printf("%d %+v\n", n, *i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment