首页 > 解决方案 > 如何使函数接收不同类型的字符串

问题描述

在我的代码中,我有一些字符串类型,例如:

type StringTypeOne string
type StringTYpeOwn string

我知道我可以在阅读后将它们转换为字符串: Converting a custom type to string in Go

但是我想写一个函数来接受所有这些类型的结构,例如

func handleString(s StringType)

其中 s 可以是StringTypeOneStringTypeTwo任何其他带有字符串字段的类型。

这在golang中可能吗?

标签: go

解决方案


你不能。但是为了您的目的,您应该实现一个自定义接口。

// 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) {
}

此方法可以同时接收StringTypeOneStringTypeTwo作为参数接收。


推荐阅读