不能在 golang 中使用范围

由于某种原因,我无法用范围迭代


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的typeFileSystemStore


type FileSystemStore map[string]FileSystemStoreEntry


type FileSystemStoreEntry struct {

    FS FileSystem

    Stored int64

}


添加到datasessionStore


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

    s := sessionStore[id]

    s.FS = memfs

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


    memfs.ReplaceFS(memory.CreateMemoryFileSystem().MFileSystem)

}

读数data


func 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


宝慕林4294392
浏览 129回答 1
1回答

慕田峪4524236

我看到的是,您的保存逻辑是错误的,我怀疑您无法迭代地图,因为它实际上是空的。这里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(),    //....}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go