相关疑难解决方法(0)

如何在Go中执行结构的深层副本?

我正在尝试执行以下结构的深层副本:

// Ternary Tree
type Tree struct {
    Left  *Tree
    Mid *Tree
    Right *Tree
    Value interface{}
    Parent *Tree
    Orientation string
    IsTerminal bool
    Type string
}
Run Code Online (Sandbox Code Playgroud)

以下是我的抱歉尝试.看起来我在根处创建了一个新树,但它的子节点仍指向内存中的相同地址.

func (tree *Tree) CopyTree() *Tree {
    if (tree == nil) {
        return nil
    } else {
        copiedTree := &Tree {
            tree.Left.CopyTree(),
            tree.Mid.CopyTree(),
            tree.Right.CopyTree(),
            tree.Value,
            tree.Parent.CopyTree(),
            tree.Orientation,
            tree.IsTerminal,
            tree.Type}
        return copiedTree
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有任何有用的结构可以帮助深度复制结构?如果没有,我将如何自己执行此深层复制?请注意," deepcopy "包不再有效,因为它使用了Go 1版本弃用的一些函数

deep-copy go

10
推荐指数
1
解决办法
9891
查看次数

在golang/reflect中访问未导出的字段?

有没有办法使用Reflect访问go 1.8中未导出的字段?这似乎不再起作用:https://stackoverflow.com/a/17982725/555493

请注意,reflect.DeepEqual工作正常(也就是说,它可以访问未导出的字段),但我无法做出该功能的正面或反面.这是一个go playarea,它显示了它的实际效果:https://play.golang.org/p/vyEvay6eVG.src代码如下

import (
"fmt"
"reflect"
)

type Foo struct {
  private string
}

func main() {
    x := Foo{"hello"}
    y := Foo{"goodbye"}
    z := Foo{"hello"}

    fmt.Println(reflect.DeepEqual(x,y)) //false
    fmt.Println(reflect.DeepEqual(x,z)) //true
}
Run Code Online (Sandbox Code Playgroud)

reflection go private-members

9
推荐指数
3
解决办法
7547
查看次数

在golang中深度检查对象的更快方法

我在用go 1.9.而且我想将对象的深度复制到另一个对象中.我尝试使用encoding/gob和encoding/json来完成它.但是gob编码需要比json编码更多的时间.我看到一些像这样的其他问题,他们建议gob编码应该更快.但我看到完全相反的行为.有人能告诉我,如果我做错了吗?或者比这两个更好更快的深度复制方法?我的对象的结构是复杂和嵌套的.

测试代码:

package main

import (
    "bytes"
    "encoding/gob"
    "encoding/json"
    "log"
    "time"

    "strconv"
)

// Test ...
type Test struct {
    Prop1 int
    Prop2 string
}

// Clone deep-copies a to b
func Clone(a, b interface{}) {

    buff := new(bytes.Buffer)
    enc := gob.NewEncoder(buff)
    dec := gob.NewDecoder(buff)
    enc.Encode(a)
    dec.Decode(b)
}

// DeepCopy deepcopies a to b using json marshaling
func DeepCopy(a, b interface{}) {
    byt, _ := json.Marshal(a)
    json.Unmarshal(byt, b)
}

func main() {
    i := 0 …
Run Code Online (Sandbox Code Playgroud)

encoding json deep-copy go gob

7
推荐指数
1
解决办法
1万
查看次数

如何使用未导出的字段克隆结构?

如果我的类型定义为:

type T struct {
    S  string
    is []int
}
Run Code Online (Sandbox Code Playgroud)

那我怎么去克隆这种类型的对象呢?如果我做一个简单的任务:

p := T{"some string", []int{10, 20}}
q := p
Run Code Online (Sandbox Code Playgroud)

然后对[]int影响两个对象的任何更改.由于T.is未导出,因此即使使用反射提取也无法显式复制.

我正在提供Clone类型本身的包中的方法.但这对其他软件包中的类似类型没有帮助.还有另一种方法吗?

struct clone go

5
推荐指数
1
解决办法
1979
查看次数

标签 统计

go ×4

deep-copy ×2

clone ×1

encoding ×1

gob ×1

json ×1

private-members ×1

reflection ×1

struct ×1