如何传递包含Golang中基本多态性的结构数组
我正在学习Golang,下面有个问题 我们有一个基本结构和另外两个基本结构,其中包含基本的。 是否可以编写一个func,它需要一个基本结构的数组,但调用该func时提供另外两个数组?请参见下面的示例如何传递包含Golang中基本多态性的结构数组,go,Go,我正在学习Golang,下面有个问题 我们有一个基本结构和另外两个基本结构,其中包含基本的。 是否可以编写一个func,它需要一个基本结构的数组,但调用该func时提供另外两个数组?请参见下面的示例 // Pathable provide path property type Pathable struct { path string } // File sturcture type File struct { name string Pathable } // Di
// 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")
}
}
上述代码引发异常无法将pathables(类型为[]File的变量)用作ifPathAlreadyExist
调用中ifPathAlreadyExist
的参数中的[]可路径值
我认为可以为每个结构创建包装器的func,其中包含可路径:这些包装器只需将提供的结构数组转换为可路径数组,然后调用上面的implementedifPathAlreadyExist
func即可。但我觉得这是错误的方式
因此,实际上我的问题是如何以正确的方式实现ifPathAlreadyExist
,以避免对每个结构重复该方法,其中包含Pathable
结构
感谢您的关注和帮助 你可以用它。这是:
你可以用它。这是:
您的示例是go的完美用例。Go并没有为您提供通过其内部结构统一实体的机会,相反,您可以通过其行为来实现
因此,在您的示例中,只有三种不同的结构,
可路径
到文件
不会使其成为可路径
,尽管文件
将继承可路径
方法 您的示例是go的完美用例。Go并没有为您提供通过其内部结构统一实体的机会,相反,您可以通过其行为来实现因此,在您的示例中,只有三种不同的结构,
可路径
到文件
不会使其成为可路径
,尽管文件
将继承可路径
方法 谢谢你的回复。我理解了你的代码,但我说的对吗?如果我们有一个文件的切片,但不是可路径的,我们应该手动转换它(通过循环?),然后作为参数传递到我提供的示例中的printPaths
?@PavelSavushkin--yes,由于文件
本身没有实现可路径
接口,只有指针*文件
实现,但是您可以将GetPath
函数签名更改为func(p PathableImpl)GetPath()字符串
,然后您可以对文件
和*文件
使用打印pahts
。注意,签名的这种更改对于getter方法来说是可以的,但对于setter则不行——因为我知道,函数总是接收对象的副本作为参数。谢谢你的帮助,今天晚上我来试试。目前我没有机会这样做。谢谢回复。我理解了你的代码,但我说的对吗?如果我们有一个文件的切片,但不是可路径的,我们应该手动转换它(通过循环?),然后作为参数传递到我提供的示例中的printPaths
?@PavelSavushkin--yes,由于文件
本身没有实现可路径
接口,只有指针*文件
实现,但是您可以将GetPath
函数签名更改为func(p PathableImpl)GetPath()字符串
,然后您可以对文件
和*文件
使用打印pahts
。注意,签名的这种更改对于getter方法来说是可以的,但对于setter则不行——因为我知道,函数总是接收对象的副本作为参数。谢谢你的帮助,今天晚上我来试试。目前我没有机会这样做。谢谢你的回复。因此,正如您所说,Grigoriy Mikhalkin提供了一个示例,我们应该为Pathable
struct实现一个访问器,并将其嵌入到其他结构中。但据我所知,函数只需要接口,而不是结构。所以,在这种情况下,我应该手动实现转换结构到接口切片,对吗?谢谢你的回复。因此,正如您所说,Grigoriy Mikhalkin提供了一个示例,我们应该为Pathable
struct实现一个访问器,并将其嵌入到其他结构中。但据我所知,函数只需要接口,而不是结构。所以,在这种情况下,我应该手动实现转换结构到接口切片,对吗?
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"}}
}
)
}