gostructcopy : 复制相似的结构体

安装: go get github.com/rocket049/gostructcopy

调用函数:

func StructCopy(src, dst interface{}) error

利用 reflect 技术把结构体 src 的可 export 值复制到 dst 中,dst 必须是相似结构体的指针,参数 src 既可以是值也可以是指针。
例如:

        a := struct {
		Id     int
		Name   string
		Weight int
		a      int
	}{100, "Dog", 200, 9}
	b := struct {
		Id   int
		Name string
		Desc string
		b    int
	}{}
	err := StructCopy(&a, &b)
        //...

共 2 个回复


buguang01

效率怎么样?

# 0

rocket

看测试数据吧:

go test -bench=.
goos: linux
goarch: amd64
pkg: github.com/rocket049/gostructcopy
BenchmarkStructCopy-4   	 2000000	       971 ns/op
PASS
ok  	github.com/rocket049/gostructcopy	2.932s

系统环境:

 OS: Ubuntu 18.04 bionic
 Kernel: x86_64 Linux 4.18.0-20-generic
 Uptime: 3h 34m
 Packages: 2682
 Shell: bash
 Resolution: 1920x1080
 DE: MATE 1.20.0
 WM: Metacity (Marco)
 GTK Theme: 'Ambiant-MATE' [GTK2/3]
 Icon Theme: Ambiant-MATE
 Font: Ubuntu 11
 CPU: Intel Core i5-5300U @ 4x 2.9GHz [42.0°C]
 GPU: Mesa DRI Intel(R) HD Graphics 5500 (Broadwell GT2) 
 RAM: 1610MiB / 7851MiB
# 1