doukeng1922 2018-05-31 12:58
浏览 112
已采纳

无法运行多个Go文件

I have two go files in a directory.

  Go  
   ├── mains.go  
   └── vars.go

The code for the mains.go and vars.go are given below:

mains.go
--------
package main

import "fmt"

func main() {
     fmt.Println("This is the mains file")
}


vars.go
--------
package main

import "fmt"

func main() {
     fmt.Println("This is the vars file")
}

While running the file individually using the terminal command

go run mains.go
go run vars.go

I am getting the output. When I am using VScode, I am getting the following error

main redeclared in this block
previous declaration at ./mains.go:5:6

Due to this error, I am not able to run the code. The code runs fine when each file is separated into folders. I tried to remove the main declaration from the file before saving but the autocomplete/autoformat feature fills the package main & import "fmt" commands automatically. My doubts are :

  • Is this the problem with the editor? (As the terminal commands run fine)

  • Any other recommended IDE for go?

My specs

Ubuntu : 16.04
Visual Studio Code : 1.23.1
go version : 1.9.2

  • 写回答

2条回答 默认 最新

  • douchensou6969 2018-06-01 08:48
    关注

    It doesn't make sense to redeclare the main function twice in the same package. You mentioned that the code works fine placing the mains.go and vars.go files in separate folders. That is expected and this is what needs to be done - placing the files in different folders.

    If however, you need to run both functions, change your setup using a simple goroutine as defined below:

    // main.go
    package main
    
    import (
              "fmt"
              "sync"
    )
    
    var wg sync.WaitGroup
    
    func main() {
         fmt.Println("This is the mains file")
    
         wg.Add(1)
         go vars()
    
         // do other stuff...
         wg.Wait()
    }
    
    // vars.go
    package main
    
    import "fmt"
    
    func vars() {
         fmt.Println("This is the vars file")
         // do other stuff...
    
         wg.Done()
    }
    

    This would allow you to run both functions at the same time whilst still in the same package. Since the functions can't have the same function name: main(), you need to change one of them to something else as I've done.

    Note however that you could simply call the vars() function without doing so concurrently.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?