golang 结构体断言

笔者的文章同时发布于 kubeclub
云原生技术社区,一个分享云原生生产经验,同时提供技术问答的平台,前往查看

一、前言

结构体断言用于判断2个对象是否属于同一类型,下面借助 kubectl 中 cp 命令的部分源码进行描述。

二、代码上下文说明

kubectl cp 功能可以将本地文件上传到远端的容器,也可以将远端容器内的文件下载到本地,所以这边涉及到2个路径,该文章也将围绕这2个路径展开讲解。

// 拷贝本地文件到容器
kubectl cp demo.txt default/podname-xxx:demo.txt
// 拷贝容器内文件到本地
kubectl cp default/podname-xxx:demo.txt demo.txt 
  1. 本地文件路径:localpath demo.txt
  2. 远端文件路径:remotepath default/podname-xxx:demo.txt demo.txt

主要源码

type fileSpec struct {
 PodName      string
 PodNamespace string
 File         pathSpec
}

type pathSpec interface {
 String() string
}
type localPath struct {
 file string
}
func (p localPath) String() string {
 return p.file
}
type remotePath struct {
 file string
}
func (p remotePath) String() string {
 return p.file
}

三、剖析

  1. 将文件路径抽象为一个顶层的 fileSpec 对象
  2. fileSpec 里面有具体的文件路径 File
  3. File 是一个 pathSpec 接口
  4. localpath 与 remotepath 都实现了这个接口,都是 File 实例。

所以这边可以看出,通过接口 golang 也是可以实现 java 的多态

func (p localPath) String() string {
 return p.file
}
func (p remotePath) String() string {
 return p.file
}
  1. 具体使用
// 解析 cp 命令的第一个参数转换为 源的 fileSpec 对象
srcSpec, err := extractFileSpec(args[0])
// 解析 cp 命令的第二个参数转换为 目标的 fileSpec 对象
destSpec, err := extractFileSpec(args[1])

// src.File 取出该对象的具体路径信息,并判断是不是 localpath 类型的地址
srcFile := src.File.(localPath)
// dist.File 取出该对象的具体路径信息,并判断是不是 remotepath 类型的地址
destFile := dest.File.(remotePath)
  1. 断言的具体使用
    对象.(要判断的类型)
  2. 上面步骤 5 的代码是拷贝文件到容器里面的,所以第一个参数只能是 localpath 类型,如果断言出错就代表着用户输入的参数信息有误。

四、小结

列举了 kubectl 里面一小部分代码,介绍了结构体断言的使用,并提到 golang 通过接口实现多态的可能。

笔者的文章同时发布于 kubeclub
云原生技术社区,一个分享云原生生产经验,同时提供技术问答的平台,前往查看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值