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

不能在 golang 中使用范围

不能在 golang 中使用范围

Go
宝慕林4294392 2022-08-01 10:24:15
由于某种原因,我无法用范围迭代var sessionStore = make(FileSystemStore)func LsSessionsCommand(_ []string, _ *string, _ *memory.FileSystem){    w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)    fmt.Fprint(w, "id\tstored time\n")        for key, val := range sessionStore {        // never reaches here        t := time.Unix(val.Stored, 0)        createdTime := fmt.Sprintf("%d:%d %d/%d/%d", t.Hour(), t.Minute(), t.Day(), t.Month(), t.Year())        _, err := fmt.Fprintf(w, "%s\t%s\n", key, createdTime)        if err != nil {            fmt.Printf("unable to list sessions: %v", err)        }    }    err := w.Flush()    if err != nil {        fmt.Printf("unable to list sessions: %v", err)    }}sessionStore的typeFileSystemStoretype FileSystemStore map[string]FileSystemStoreEntrytype FileSystemStoreEntry struct {    FS FileSystem    Stored int64}添加到datasessionStorefunc StashSession(memfs memory.FileSystem, id string) {    s := sessionStore[id]    s.FS = memfs    s.Stored = time.Now().Unix()    memfs.ReplaceFS(memory.CreateMemoryFileSystem().MFileSystem)}读数datafunc CollectSession(memfs memory.FileSystem, id string, stashCurrent bool, newid string) {    s := sessionStore[id]    fs := s.FS.MFileSystem    if stashCurrent {        s.FS = memfs    }    memfs.ReplaceFS(fs)}我可以和数据,但不能迭代它。当我调用输出时,我得到它只是永远不会到达范围函数的主体。readwritesessionStoreLsSessionsCommand()id    stored time我先叫函数,再叫函数StashSessionLsSessionsCommand
查看完整描述

1 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

我看到的是,您的保存逻辑是错误的,我怀疑您无法迭代地图,因为它实际上是空的。


这里


func StashSession(memfs memory.FileSystem, id string) {

    s := sessionStore[id]

    s.FS = memfs

    s.Stored = time.Now().Unix()

    //...

}

您没有在地图中添加新元素。为此,您需要:


sessionStore[id] = FileSystemStoreEntry{

    FS: memfs,

    Stored: time.Now().Unix(),

    //....

}


查看完整回答
反对 回复 2022-08-01
  • 1 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号