如何将地图值传递到其他文件

file1

func loopFunc() {
    m := make(map[int]net.Conn)
    for i := 1; i < 10000; i++ {
        c, err := l.Accept()
        if err != nil {
            fmt.Println(err)
            return
        }
        m[i] = c
    }
    iWantMaps(m)
}

file2 doesn't exist yet, but a random assigning to a value from the map will do as an example

func iWantMaps(m) {
    something := m[1]
}

This is my project structure:

+/pkg
+-->file1
+-->file2

Consider a for loop that constantly updates a map in file1. I'm trying to either:

  • transfer the whole map from file1 to a function in file2
  • be able to retrieve keys and values from the map in file1 from a function in file2.

I am not entirely sure what you are trying to do, but from my understanding, you want to ensure that the function in the second file can access the map from the function in the first file, correct?

For simplicity, I will call fn1 the function that lives in file 1, and fn2 the function that lives in file 2.

The fact that they are not in different files should not affect anything, as long as they have access to each other. One alternative is to declare your map in the parent function (the function that calls both your fn1 and fn2) and then pass this map as an argument for both functions. For example:

func fn1(sessionMap map[int]int) {
    for i := 1; i < 10000; i++ {
        // do some work here
        sessionMap[i] = i
    }
}

func fn2(sessionMap map[int]int) {
    for i := 1; i < 10000; i++ {
        fmt.Println(sessionMap[i])
    }
}

func main() {
    sessionMap := make(map[int]int)
    fn1(sessionMap)
    fn2(sessionMap)
}

If, however, fn2 is being called by fn1, you can declare the map in fn1 and pass it to fn2 like this:

func fn1() {
    sessionMap := make(map[int]int)

    for i := 1; i < 10000; i++ {
        // do some work here
        sessionMap[i] = i
    }

    fn2(sessionMap)
}

func fn2(sessionMap map[int]int) {
    for i := 1; i < 10000; i++ {
        fmt.Println(sessionMap[i])
    }
}


func main() {
    fn1()
}

fn1 and fn2 can both live in separate or the same files.

Cheers