dongpingwu8378 2018-12-08 21:15
浏览 12
已采纳

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

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.
  • 写回答

1条回答 默认 最新

  • dspv70887 2018-12-08 21:39
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像