Map似乎在递归中丢弃值

问题描述 投票:1回答:1

我一直在研究一个问题,我想我会用口袋妖怪设置来演示它。我正在读取文件,解析文件并从中创建对象/结构。这通常不是问题,除了现在我需要实现像继承traits这样的接口。我不希望那里有重复的技能,所以我想我可以使用地图来复制一组数据结构。然而,似乎在我的递归parsePokemonFile函数的传递阶段(参见implementsComponent情况),我似乎在我的地图中丢失了值。

我正在使用这样的输入:

4个文件

Ratatta:

name=Ratatta
skills=Tackle:normal,Scratch:normal

妙蛙种子:

name=Bulbosaur
implements=Ratatta
skills=VineWhip:leaf

简单:

name=Oddish
implements=Ratatatt
skills=Acid:poison

妙蛙花:

name=Venosaur
implements=bulbosaur,oddish

我期待以下代码的输出类似于

Begin!
{Venosaur [{VineWhip leaf} {Acid poison} {Tackle normal} {Scratch normal}]}

但我得到了

Begin!
{Venosaur [{VineWhip leaf} {Acid poison}]}

我究竟做错了什么?这可能是一个逻辑错误吗?或者我是否假设我不应该持有价值的地图?

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

// In order to create a set of pokemon abilities and for ease of creation and lack of space being taken up
// We create an interfacer capability that imports the skills and attacks from pokemon of their previous evolution
// This reduces the amount of typing of skills we have to do.
// Algorithm is simple. Look for the name "implements=x" and then add x into set.
// Unfortunately it appears that the set is dropping values on transitive implements interfaces

func main() {
     fmt.Println("Begin!")
    dex, err := parsePokemonFile("Venosaur")
    if err != nil {
        fmt.Printf("Got error: %v\n", err)
    }
    fmt.Printf("%v\n", dex)
}

type pokemon struct {
    Name   string
    Skills []skill
}

type skill struct {
    SkillName string
    Type      string
}

func parsePokemonFile(filename string) (pokemon, error) {
    file, err := os.Open(filename)
    if err != nil {
        return pokemon{}, err
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    var builtPokemon pokemon
    for scanner.Scan() {
        component, returned := parseLine(scanner.Text())
        switch component {
        case nameComponent:
            builtPokemon.Name = returned
        case skillsComponent:
            skillsStrings := strings.Split(returned, ",")
            var skillsArr []skill
            // split skills and add them into pokemon skillset
            for _, skillStr := range skillsStrings {
                skillPair := strings.Split(skillStr, ":")
                skillsArr = append(skillsArr, skill{SkillName: skillPair[0], Type: skillPair[1]})
            }
            builtPokemon.Skills = append(builtPokemon.Skills, skillsArr...)
        case implementsComponent:
            implementsArr := strings.Split(returned, ",")
            // create set to remove duplicates
            skillsSet := make(map[*skill]bool)
            for _, val := range implementsArr {
                // recursively call the pokemon files and get full pokemon
                implementedPokemon, err := parsePokemonFile(val)
                if err != nil {
                    return pokemon{}, err
                }
                // sieve out the skills into a set
                for _, skill := range implementedPokemon.Skills {
                    skillsSet[&skill] = true
                }
            }
            // append final set into the currently being built pokemon
            for x := range skillsSet {
                builtPokemon.Skills = append(builtPokemon.Skills, *x)
            }
        }
    }
    return builtPokemon, nil
}

type component int

// components to denote where to put our strings when it comes time to assemble what we've parsed
const (
    nameComponent component = iota
    implementsComponent
    skillsComponent
)

func parseLine(line string) (component, string) {
    arr := strings.Split(line, "=")
    switch arr[0] {
    case "name":
        return nameComponent, arr[1]
    case "implements":
        return implementsComponent, arr[1]
    case "skills":
        return skillsComponent, arr[1]
    default:
        panic("Invalid field found")
    }
}
go maps logic
1个回答
3
投票

这与Golang地图丢弃任何值无关。

问题是你正在使用技能指针而不是技能。指向相同技能内容的两个指针可以是不同的。

skillsSet := make(map[*skill]bool)

如果你把它改成map[skill]bool,这应该有效。你可以尝试一下!

© www.soinside.com 2019 - 2024. All rights reserved.