惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
B
Blog
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
爱范儿
爱范儿
博客园_首页
博客园 - 聂微东
量子位
V
Visual Studio Blog
aimingoo的专栏
aimingoo的专栏
T
The Blog of Author Tim Ferriss
J
Java Code Geeks
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
Netflix TechBlog - Medium
F
Fortinet All Blogs
The Cloudflare Blog
T
Tailwind CSS Blog
G
Google Developers Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
腾讯CDC

博客园 - calochCN

using webpack5 ubuntu 如何将任何app run为服务 这里想配置一下mysql主从,并归档,以备使用 hotkey resizer, rect win small app using C, tool utils Using ES6 Module In Browser. reprint, Use of logrotate go get net/http connections count, using middleware 手动数据库分库分片策略 记录一下ubuntu 挂载一下raid1 硬盘的过程 好久不弄css导航条,这里再布一下 sapui5 说说备案问题,说说发现的腾讯云和gitee这些国内服务商,使用过程中发现的一些猫腻 我最近觉得自己的收藏夹很乱,因为没有事情做,就想闲着给自己做个网址导航的软件【一】 学日语看到一个笑话 抽几分钟,写个文档系统的前端页面,先排版一下. 文字竖排,从上到下排列,仿古文的写法 从前做前端的时候, 联通的好多html5活动, 页面布局如何整齐,回顾一个常用的 我依然没有用quest2串流过一次... 这次还是决定好好用hugo写一下模板系统
go copy object deep深拷贝
calochCN · 2025-10-06 · via 博客园 - calochCN

GOLANG 深拷贝:

package main

import (
    "fmt"
    "reflect"
)

func DeepCopy(src interface{}) interface{} {
    if src == nil {
        return nil
    }
    srcVal := reflect.ValueOf(src)
    if srcVal.Kind() == reflect.Ptr && srcVal.IsNil() {
        return nil
    }
    copy := reflect.New(srcVal.Type()).Elem()
    deepCopyRecursive(srcVal, copy)
    return copy.Interface()
}

func deepCopyRecursive(src, dst reflect.Value) {
    switch src.Kind() {
    case reflect.Ptr:
        if src.IsNil() { return }
        dst.Set(reflect.New(src.Elem().Type()))
        deepCopyRecursive(src.Elem(), dst.Elem())
    case reflect.Slice:
        if src.IsNil() { return }
        dst.Set(reflect.MakeSlice(src.Type(), src.Len(), src.Cap()))
        for i := 0; i < src.Len(); i++ {
            deepCopyRecursive(src.Index(i), dst.Index(i))
        }
    case reflect.Map:
        if src.IsNil() { return }
        dst.Set(reflect.MakeMap(src.Type()))
        for _, key := range src.MapKeys() {
            val := src.MapIndex(key)
            copyVal := reflect.New(val.Type()).Elem()
            deepCopyRecursive(val, copyVal)
            dst.SetMapIndex(key, copyVal)
        }
    case reflect.Struct:
        for i := 0; i < src.NumField(); i++ {
            deepCopyRecursive(src.Field(i), dst.Field(i))
        }
    default:
        dst.Set(src)
    }
}

type Address struct{ City string }
type Person struct {
    Name    string
    Address *Address
}

func main() {
    orig := &Person{Name: "Alice", Address: &Address{City: "Paris"}}
    copy := DeepCopy(orig).(*Person)
    copy.Address.City = "Berlin"
    fmt.Printf("Original: %+v\n", orig.Address) // 输出Paris
    fmt.Printf("Copy: %+v\n", copy.Address)     // 输出Berlin
}