go - 如何传递结构数组,其中包含基本结构Golang中的多态性

标签 go

我正在学习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/

相关文章:

arrays - slice append 的行为异常

image - 如何确定 png "type"(png8/png24)

json - 解码一个 json 流(不是换行符分隔的)

匹配没有小写字母且至少有一个大写字母的正则表达式?

go - 解释 pprof 堆图

go - json.Unmarshal 在进行 curl 调用时不填充结构

arrays - 在 Go 中序列化混合类型的 JSON 数组

go - CORS 请求未应用正确的 Golang

algorithm - Go:用于字符串比较的多项式指纹

go - 如何阻止html模板转义