将读/写/保存从映射结构保存到 json



我一直在尝试拥有一个"工作"文件,我将应用程序的某些基本状态保存到该文件中,而不是将它们保存在 Ram 中,因为它们需要每天保存,我决定每天创建文件,这部分正在工作,但我已将其从代码中删除以更清晰。

现在,我能够为信息结构体使用 false 值初始化我的文件,然后解组并从中读取。

当我在将"文件">

保存回文本文件之前,在解组后尝试更新"文件"时,会出现问题。

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")
}
func ImportStart(symbol string){
filename := "test.txt"
_, err := os.Stat(filename)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("File does not exist creating it...")
file, err := os.Create(filename)
jsonString, _ := json.Marshal(MyList)
writeFile(string(jsonString),filename)
if err != nil {
fmt.Println(err)
}
fmt.Println("reading from file"+filename )
x := ReadFile(filename)
var TheList = map[string]Informations{}
json.Unmarshal(x,&TheList )
TheList[symbol].ImportStarted = true
defer file.Close()
//wanting to save afterwards...
}
} else {
fmt.Println("reading from file "+ filename)
x := ReadFile(filename)
var TheList = map[string]Informations{}
json.Unmarshal(x,&TheList )
&TheList[symbol].ImportStarted = true
}
}

func isImportStarted(symbol string) bool{
filename := "test.txt"
x := ReadFile(filename)
var TheList = map[string]Informations{}
json.Unmarshal(x,&TheList )
return TheList[symbol].ImportStarted
}

我已经尝试过为什么将结构的值设置为映射中的值时出现"无法分配"错误? 问题,但它根本不适合我的用例,因为它会有效地用 nil 而不是 {false,false} 初始化我的所有结构

有什么想法吗?

尝试var TheList = map[string]*Informations{},为什么你不能在映射中分配值,请参考为什么-do-i-get-a-cannot-assing-error或access-struct-in-map-without-copy

最新更新