go - 如何使函数接收不同类型的字符串
问题描述
在我的代码中,我有一些字符串类型,例如:
type StringTypeOne string
type StringTYpeOwn string
我知道我可以在阅读后将它们转换为字符串: Converting a custom type to string in Go
但是我想写一个函数来接受所有这些类型的结构,例如
func handleString(s StringType)
其中 s 可以是StringTypeOne
或StringTypeTwo
任何其他带有字符串字段的类型。
这在golang中可能吗?
解决方案
你不能。但是为了您的目的,您应该实现一个自定义接口。
// define an interface that do something you need
type Doer interface {
DoSomething();
}
然后定义自定义类型并实现已定义接口的所有必要功能:
type StringTypeOne string
type StringTypeTwo string
func (s StringTypeOne) DoSomething() {
}
func (s StringTypeTwo) DoSomething() {
}
然后您可以创建接收接口作为参数的函数:
func handleString(s Doer) {
}
此方法可以同时接收StringTypeOne
或StringTypeTwo
作为参数接收。
推荐阅读
- python - 在 djnago 模板中动态填充具有子类别的类别菜单
- javascript - 仅选择日期时如何配置 datetimepicker 以正常工作
- mysql - mysql - 如何从两个不同的提供者检索两个不同的时间间隔?
- mysql - 使用多年后使用 GROUPBY 的 MySQL 查询失败
- android - ActionBar Android 透明
- javascript - 从数组中获取两个随机的非连续且唯一的元素
- jenkins - 如何在位于从站的詹金斯自由式作业中使用“可扩展选择参数”来显示文件
- r - 在 R 中合并两个数据帧 - 值被替换为 NA
- c# - CategoryAxis - 修剪字符串,同时保留具有完整信息的工具提示数据
- python - 使用pygame减少对象之间的距离