登录
首页 >  Golang >  Go问答

在 Golang 中如何处理包含基本结构的数组

来源:stackoverflow

时间:2024-02-27 16:39:24 461浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《在 Golang 中如何处理包含基本结构的数组》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在学习 golang,有一个问题如下。

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

// 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 ([]file 类型的变量) 作为 ifpathalreadyexist 调用的 ifpathalreadyexist 参数中的 []pathable 值。

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

所以,实际上我的问题是如何以正确的方式实现 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 interface 的完美用例。go 不为您提供通过其内部统一实体的机会,相反您可以通过其行为来做到这一点。
因此,在您的情况下,只有三种不同的结构,并且 embedding pathablefile 不会使其成为 pathable,尽管 file 将继承 pathable 方法。

以上就是《在 Golang 中如何处理包含基本结构的数组》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>