我正在学习Golang,下面有一个问题。
我们有一个基本结构,另外两个有基本结构。
是否可以编写一个期望有一个基本结构数组的func,但是可以通过提供另外两个来调用该func?请参见下面的示例。
// 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")
}
}
上面的代码在
cannot use pathables (variable of type []File) as []Pathable value in argument to ifPathAlreadyExist
调用上抛出异常ifPathAlreadyExist
。我想有可能为每个包含Pathable的结构创建包装器的func:这些包装器仅将提供的结构数组转换为Pathable,并仅调用上述已实现的
ifPathAlreadyExist
func。但是我觉得这是错误的方式。因此,实际上我的问题是如何以正确的方式实现
ifPathAlreadyExist
,以避免为每个结构(该结构内部包含Pathable
结构)重复该方法?感谢您的关注和帮助!
最佳答案
您可以为此使用interfaces。这是example:
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 - 如何传递结构数组,其中包含基本结构Golang中的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61572797/