go - 使用递归函数迭代递归结构

标签 go

我有以下结构

    type Sitemap struct {
        XMLName        xml.Name `xml:"urlset"`
        Namespace      string   `xml:"xmlns,attr"`
        Schema         string   `xml:"xmlns:xsi,attr"`
        SchemaLocation string   `xml:"xsi:schemaLocation,attr"`
        Root           *URLItem
    }

    type URLItem struct {
        XMLName xml.Name `xml:"url"`
        Loc     string   `xml:"loc"`
        LastMod string   `xml:"lastmod,omitempty"`
        Urls    []*URLItem
    }

    func (s *Sitemap) AddURL(key string, url string) {
        node, found := findURLItemRecursive(s.Root, key)
        if found {
            node.Urls = append(node.Urls, &URLItem{Loc: url})
        }
    }


    func findURLItemRecursive(urlItem *URLItem, key string) (*URLItem, bool) {
        if urlItem.Loc == key {
            return urlItem, true
        }

        for _, urlItem := range urlItem.Urls {
            return findURLItemRecursive(urlItem, key)
        }

        return nil, false
    }

其中 key 是父 URL,url 是链接到父 URL 的子 URL,因为子 URL 位于 parent 。

由于某些未知原因,findURLItemRecursive 有问题。

问题是我无法在第二级附加更多 UrlItem(s)。

我的意思是我可以创建 Root 项,为 Root 项创建 Urls slice ,但我无法创建嵌套 slice 。所以我不能超过第一级。

我想知道函数 findURLItemRecursive 在 Go 中是否有任何我无法发现的明显错误。

最佳答案

我认为这应该适合您。

    type Sitemap struct {
        XMLName        xml.Name `xml:"urlset"`
        Namespace      string   `xml:"xmlns,attr"`
        Schema         string   `xml:"xmlns:xsi,attr"`
        SchemaLocation string   `xml:"xsi:schemaLocation,attr"`
        Root           *URLItem
    }

    type URLItem struct {
        XMLName xml.Name `xml:"url"`
        Loc     string   `xml:"loc"`
        LastMod string   `xml:"lastmod,omitempty"`
        Urls    []*URLItem
    }

    func (s *Sitemap) AddURL(key string, url string) {
        node, found := findURLItemRecursive(s.Root, key)
        if found {
            node.Urls = append(node.Urls, &URLItem{Loc: url})
        }
    }


    func findURLItemRecursive(urlItem *URLItem, key string) (*URLItem, bool) {
        if urlItem.Loc == key {
            return urlItem, true
        }

        for _, urlItem := range urlItem.Urls {
            item, found := findURLItemRecursive(urlItem, key)
            if found {
                return item, found
            }
        }

        return nil, false
    }

关于go - 使用递归函数迭代递归结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826731/

相关文章:

go - 是否可以组合多个 SHA1 状态来获得 Golang 中的最终状态?

go - 为什么Go编程中没有while循环?试图让用户输入数字1到12?

go - 给定另一个动态修改 Golang struct{} 值的属性

Golang 单元测试矩阵在 SonarQube 仪表板上不可见

go - slice 索引奇怪的边缘情况

go - 在未导出的字段上调用导出的方法

go - CGO 库构建到 JS WASM 文件

在 Golang 中测试/模拟 3rd 方包

json - 如何编写一个 Go 函数来接受不同的结构?

go - Redigo:在 Apache 负载测试中出现错误