如何传递包含基本结构的数组| Golang中的多态性



我正在学习Golang,下面有一个问题。

我们有一个基本结构和另外两个基本结构,其中包含基本结构。是否可以编写一个函数,它需要一个基本结构的数组,但调用该函数时提供另外两个?请参阅下面的示例。

// Pathable provide path property
type Pathable struct {
path string
}
// File sturcture
type File struct {
name string
Pathable
}
// Directory structure
type Directory struct {
name        string
files       []File
directories []Directory
Pathable
}
// Detect if provided directories contain specified path
func ifPathAlreadyExist(entities []Pathable, path string) bool {
for _, entity := range entities {
if entity.path == path {
return true
}
}
return false
}
func main() {
pathables := []File{
File{
name: "some_file.txt",
Pathable: Pathable{
path: "test_path/to/file",
},
},
}
localPath := "some/path"
if ifPathAlreadyExist(pathables, localPath) {
fmt.Println("Exist")
}
}

上面的代码在ifPathAlreadyExist调用上抛出一个异常cannot use pathables (variable of type []File) as []Pathable value in argument to ifPathAlreadyExist

我想可以为每个包含Pathable的结构创建包装器的函数:这些包装器只需将提供的结构数组转换为Pathable结构,并调用上面实现的ifPathAlreadyExist函数。但我觉得这是错误的方式。

所以,实际上我的问题是如何以正确的方式实现ifPathAlreadyExist,以避免对每个内部包含Pathable结构的结构重复该方法?

感谢您的关注和帮助!

您可以为此使用接口。以下是示例:

type Pathable interface {
GetPath() (path string)
}
type PathableImpl struct {
path string
}
func (p *PathableImpl) GetPath() string {
return p.path
}
type File struct {
name string
PathableImpl
}
func printPaths(entities []Pathable) {
for _, entity := range entities {
fmt.Println(entity.GetPath())
}
}
func main() {
printPaths(
[]Pathable{
&PathableImpl{path:"/pathableImpl"}, 
&File{name: "file", PathableImpl: PathableImpl{path:"/file"}}
}
)
}

您的示例是go的interface的完美用例。Go并没有为你提供通过其内部结构来统一实体的机会,相反,你可以通过它的行为来实现
因此,在您的情况下,只有三种不同的结构,将Pathable嵌入到File不会使其成为Pathable,尽管File将继承Pathable方法。

最新更新