doudou201701
2013-01-04 10:15
浏览 2.2k
已采纳

如何使用Go语言从另一个文件调用函数?

I want to call function from another file in go lang, can any one help?

test1.go

package main

func main() {
    demo()
}

test2.go

package main

import "fmt"

func main() {
}

func demo() {
    fmt.Println("HI")
}

How to call demo in test2 from test1?

图片转代码服务由CSDN问答提供 功能建议

我想从go lang的另一个文件中调用函数,有谁可以帮忙吗? \ n

test1.go

 包main 
 
func main(){
 demo()
} 
   \  n 
 

test2.go

 包main 
 
import“ fmt” 
 
func main(){
} 
 
func demo()  {
 fmt.Println(“ H​​I”)
} 
   
 
 

如何从test1调用test2中的demo?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douliang1900 2013-01-04 10:17
    已采纳

    You can't have more than one main in your package.

    More generally, you can't have more than one function with a given name in a package.

    Remove the main in test2.go and compile the application. The demo function will be visible from test1.go.

    打赏 评论
  • dsg7513 2017-05-13 13:16

    Go Lang by default builds/runs only the mentioned file. To Link all files you need to specify the name of all files while running.

    Run either of below two commands:

    $go run test1.go test2.go. //order of file doesn't matter
    $go run *.go
    

    You should do similar thing, if you want to build them.

    打赏 评论
  • dongmao3131 2017-11-16 15:20

    I was looking for the same thing. To answer your question "How to call demo in test2 from test1?", here is the way I did it. Run this code with go run test1.go command. Change the current_folder to folder where test1.go is.

    test1.go

    package main
    
    import (
        L "./lib"
    )
    
    func main() {
        L.Demo()
    }
    

    lib\test2.go

    Put test2.go file in subfolder lib

    package lib
    
    import "fmt"
    
    // This func must be Exported, Capitalized, and comment added.
    func Demo() {
        fmt.Println("HI")
    }
    
    打赏 评论

相关推荐 更多相似问题