为了账号安全,请及时绑定邮箱和手机立即绑定

从地图结构保存读取/写入/保存到 json

从地图结构保存读取/写入/保存到 json

Go
湖上湖 2023-06-19 17:15:38
我一直在尝试拥有一个“工作”文件,我将我的应用程序的某些基本状态保存到其中,而不是将它们保存在 Ram 中,因为它们需要每天保存,我决定每天创建文件,这部分是工作,但为了更清楚起见,我已将其从代码中删除。现在我可以用信息结构的假值初始化我的文件,然后解组并从中读取。当我在将“文件”保存回文本文件之前对其进行解组后尝试更新它时,问题就出现了。确实isImportStarted有效(当删除错误行 obv 时)但我似乎无法正确更新文件我收到此错误:./test.go:62:34: cannot assign to struct field TheList[symbol].ImportStarted in map./test.go:71:3: cannot take the address of TheList[symbol].ImportStarted./test.go:71:34: cannot assign to &TheList[symbol].ImportStarted我的代码:                package main                import (                    "encoding/json"                    "fmt"                    "os"                    "io/ioutil"                    "log"                )                type Informations struct {                        ImportStarted bool                        ImportDone bool                }                var MyList = map[string]*Informations{                    "test": &Informations{ImportStarted: false,ImportDone:false},                    "test2": &Informations{ImportStarted: false,ImportDone:false},                }                func ReadFile(filename string) []byte{                    data, err := ioutil.ReadFile(filename)                    if err != nil {                        log.Panicf("failed reading data from file: %s", err)                    }                        return data                }                func writeFile(json string,filename string){                        file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, os.ModeAppend)                        defer file.Close()                        if err != nil {                            fmt.Println(err)                        }                        _,err2 := file.WriteString(json)                        fmt.Println(err2)                }                func main() {                        isImportStarted("test")                        ImportStart("test")                }我已经尝试过为什么在将值设置为结构作为映射中的值时出现“无法分配”错误?问题,但它根本不适合我的用例,因为它会用 nil 而不是 {false,false} 有效地初始化我所有的结构有任何想法吗?
查看完整描述

1 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

尝试var TheList = map[string]*Informations{},为什么你不能在地图中赋值。

查看完整回答
反对 回复 2023-06-19
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信