dtpwra8456 2019-02-04 03:55
浏览 6

如何在Golang中将文件行中的值分配给地图

I am trying to write a self of key value pairs, later be used as a rule engine. Here what i am trying to achieve is getting the following code to make a map called "f" and assign the values on the file line to it. However the following code throws an exception saying "f is not a type"

Is the method im doing to achieve the above task is correct? if not please suggest a better way of doing it, and better if you can provide me with a sample code How to assign the line value to the map? better if you can provide me with a sample code

Thank you in advance

rules file

"name": "hero", "age":"27
"name": "villein", "age":"30

code

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.Open("rules")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        var f = make(map[string]string)
        f {scanner.Text()}
        fmt.Println(f)
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}
  • 写回答

1条回答 默认 最新

  • dtcyv3985 2019-02-04 05:44
    关注

    Consider using JSON for the file format so you can the JSON parser in the standard library:

    [
    {"name": "hero", "age":"27"},
    {"name": "villein", "age":"30"}
    ]
    

    With this format, the code is:

    file, err := os.Open("rules")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    var data []map[string]string
    if err := json.NewDecoder(file).Decode(&data); err != nil {
        log.Fatal(err)
    }
    // variable data is a slice of maps
    

    Run it on the Playground

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b