我一直试图创建一个“工作”文件,以便将应用程序的某些基本状态保存到该文件中,而不是将其保存在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")
}
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
}
我已经尝试过Why do I get a "cannot assign" error when setting value to a struct as a value in a map?问题,但是它根本不适合我的用例,因为它将有效地用nil而不是{false,false}初始化我的所有结构
有什么想法吗?
答案 0 :(得分:0)
尝试var TheList = map[string]*Informations{}
,为什么不能在地图中分配值,请参考why-do-i-get-a-cannot-assing-error或access-struct-in-map-without-copying