百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
C

copier

> 包管理
开源

Go 语言的 Copier,将值从一个结构体复制到另一个结构体,以及更多功能

6.2K stars0 点赞4 次浏览
访问官网GitHub

工具介绍

Go 语言的 Copier,将值从一个结构体复制到另一个结构体,以及更多功能

Copier

我是一个复制器,我将所有内容从一个复制到另一个

主要特性

  • 基于名称匹配的字段到字段和方法到字段的复制
  • 支持以下数据复制:
    • 从切片到切片
    • 从结构体到切片
    • 从 map 到 map
  • 通过 tag 操作字段:
    • 使用 copier:"must" 强制复制字段
    • 即使设置了 IgnoreEmpty 也使用 copier:"override" 覆盖字段
    • 使用 copier:"-" 排除字段,不进行复制

快速开始

安装

要开始使用 Copier,请安装 Go 并运行 go get:

bash
go get -u github.com/jinzhu/copier

基础用法

在你的应用程序中导入 Copier 以使用其复制功能

go
import "github.com/jinzhu/copier"

基本复制

go
type User struct {
	Name string
	Role string
	Age  int32
}

func (user *User) DoubleAge() int32 {
	return 2 * user.Age
}

type Employee struct {
	Name      string
	Age       int32
	DoubleAge int32
	SuperRole string
}

func (employee *Employee) Role(role string) {
	employee.SuperRole = "Super " + role
}

func main() {
	user := User{Name: "Jinzhu", Age: 18, Role: "Admin"}
	employee := Employee{}

	copier.Copy(&employee, &user)
	fmt.Printf("%#v\n", employee)
	// Output: Employee{Name:"Jinzhu", Age:18, DoubleAge:36, SuperRole:"Super Admin"}
}

标签使用示例

copier:"-" - 忽略字段

带有 copier:"-" 标签的字段在复制过程中会被 Copier 明确忽略。

go
type Source struct {
    Name   string
    Secret string // We do not want this to be copied.
}

type Target struct {
    Name   string
    Secret string `copier:"-"`
}

func main() {
    source := Source{Name: "John", Secret: "so_secret"}
    target := Target{}

    copier.Copy(&target, &source)
    fmt.Printf("Name: %s, Secret: '%s'\n", target.Name, target.Secret)
    // Output: Name: John, Secret: ''
}

copier:"must" - 强制字段复制

copier:"must" 标签强制复制某个字段,如果该字段无法复制,则会导致 panic 或返回错误。

go
type MandatorySource struct {
	Identification int
}

type MandatoryTarget struct {
	ID int `copier:"must"` // 此字段必须被复制,否则会 panic 或报错。

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Gocopygogolanggolang-package

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类包管理
定价开源

> 相关工具

N
npm
Node.js 默认包管理器
P
pnpm
高效节省磁盘的 Node 包管理器
I
is-gif
Check if a Buffer/Uint8Array is a GIF image