Call a function from another package in Go

前端 未结 5 454
予麋鹿
予麋鹿 2020-12-29 17:33

I have two files main.go which is under package main, and another file with some functions in the package called functions.

My question is:

5条回答
  •  被撕碎了的回忆
    2020-12-29 18:29

    • You should prefix your import in main.go with: MyProj, because, the directory the code resides in is a package name by default in Go whether you're calling it main or not. It will be named as MyProj.

    • package main just denotes that this file has an executable command which contains func main(). Then, you can run this code as: go run main.go. See here for more info.

    • You should rename your func getValue() in functions package to func GetValue(), because, only that way the func will be visible to other packages. See here for more info.

    File 1: main.go (located in MyProj/main.go)

    package main
    
    import (
        "fmt"
        "MyProj/functions"
    )
    
    func main(){
        fmt.Println(functions.GetValue())
    }
    

    File 2: functions.go (located in MyProj/functions/functions.go)

    package functions
    
    // `getValue` should be `GetValue` to be exposed to other packages.
    // It should start with a capital letter.
    func GetValue() string{
        return "Hello from this another package"
    }
    

提交回复
热议问题