Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,37 @@
package main
import "fmt"
// a complex data structure
type cds struct {
i int // no special handling needed for deep copy
s string // no special handling
b []byte // copied easily with append function
m map[int]bool // deep copy requires looping
}
// a method
func (c cds) deepcopy() *cds {
// copy what you can in one line
r := &cds{c.i, c.s, append([]byte{}, c.b...), make(map[int]bool)}
// populate map with a loop
for k, v := range c.m {
r.m[k] = v
}
return r
}
// demo
func main() {
// create and populate a structure
c1 := &cds{1, "one", []byte("unit"), map[int]bool{1: true}}
fmt.Println(c1) // show it
c2 := c1.deepcopy() // copy it
fmt.Println(c2) // show copy
c1.i = 0 // change original
c1.s = "nil"
copy(c1.b, "zero")
c1.m[1] = false
fmt.Println(c1) // show changes
fmt.Println(c2) // show copy unaffected
}

View file

@ -0,0 +1,60 @@
package main
import "fmt"
// a type that allows cyclic structures
type node []*node
// recursively print the contents of a node
func (n *node) list() {
if n == nil {
fmt.Println(n)
return
}
listed := map[*node]bool{nil: true}
var r func(*node)
r = func(n *node) {
listed[n] = true
fmt.Printf("%p -> %v\n", n, *n)
for _, m := range *n {
if !listed[m] {
r(m)
}
}
}
r(n)
}
// construct a deep copy of a node
func (n *node) ccopy() *node {
if n == nil {
return n
}
cc := map[*node]*node{nil: nil}
var r func(*node) *node
r = func(n *node) *node {
c := make(node, len(*n))
cc[n] = &c
for i, m := range *n {
d, ok := cc[m]
if !ok {
d = r(m)
}
c[i] = d
}
return &c
}
return r(n)
}
func main() {
a := node{nil}
c := &node{&node{&a}}
a[0] = c
c.list()
cc := c.ccopy()
fmt.Println("copy:")
cc.list()
fmt.Println("original:")
c.list()
}

View file

@ -0,0 +1,62 @@
package main
import (
"encoding/gob"
"fmt"
"os"
)
// capability requested by task
func deepcopy(dst, src interface{}) error {
r, w, err := os.Pipe()
if err != nil {
return err
}
enc := gob.NewEncoder(w)
err = enc.Encode(src)
if err != nil {
return err
}
dec := gob.NewDecoder(r)
return dec.Decode(dst)
}
// define linked list type, an example of a recursive type
type link struct {
Value string
Next *link
}
// method satisfies stringer interface for fmt.Println
func (l *link) String() string {
if l == nil {
return "nil"
}
s := "(" + l.Value
for l = l.Next; l != nil; l = l.Next {
s += " " + l.Value
}
return s + ")"
}
func main() {
// create a linked list with two elements
l1 := &link{"a", &link{Value: "b"}}
// print original
fmt.Println(l1)
// declare a variable to hold deep copy
var l2 *link
// copy
if err := deepcopy(&l2, l1); err != nil {
fmt.Println(err)
return
}
// print copy
fmt.Println(l2)
// now change contents of original list
l1.Value, l1.Next.Value = "c", "d"
// show that it is changed
fmt.Println(l1)
// show that copy is unaffected
fmt.Println(l2)
}