如何在test2中调用test1的Go函数

时间:2016-12-01 09:32:19

标签: go

按以下方式输入文件

package goClientLib
import (
     ....
)
//The following function will read Command Line Inputs and will return 3 strings
func readInput() (string, string, string){
    var (clientRequest, clientId, clientPassword string)
    argsLen := len(os.Args)
    fmt.Println("Arg Length:",argsLen)
    if len(os.Args) != 4 {
        fmt.Fprintf(os.Stderr, "Usage: %s URL\n", os.Args[0])
        os.Exit(1)
    } else {
        clientRequest = strings.Join(os.Args[1:2],"")
        clientId = strings.Join(os.Args[2:3],"")
        clientPassword = strings.Join(os.Args[3:4],"")
    }

    return clientRequest, clientId, clientPassword
}

现在我尝试在Test2.go文件中使用它,如下所示:

package main
import (
    "os"
    "fmt"
    "net/http"
    "io"
    "log"
    "goClientLib"
)

func main() {
    clientRequest, clientId, clientPassword := goClientLib.readInput()
    host := goClientLib.generateRequest(clientRequest)
    fmt.Println("clientRequest:",clientRequest)
    fmt.Println("clientId:",clientId)
    fmt.Println("clientPassword:",clientPassword)
    fmt.Println("host:",host)
    response, err := http.Get(host)
    if err != nil {
        log.Fatal(err)
    } else {
        defer response.Body.Close()
        _, err := io.Copy(os.Stdout, response.Body)
        if err != nil {
            log.Fatal(err)
        }
    }
}

我正在使用以下文件结构

src/test2.go
src/goClientLib/test1.go

但是此代码在运行时给出了以下错误

# command-line-arguments
src\goClientMain.go:15: cannot refer to unexported name goClientLib.readInput
src\goClientMain.go:16: cannot refer to unexported name goClientLib.generateRequest
src\goClientMain.go:16: undefined: goClientLib.generateRequest

1 个答案:

答案 0 :(得分:3)

正如Volker所评论的,为了从另一个包中访问函数,函数名的第一个字母必须是大写。在您的情况下,将readInput()更改为ReadInput(),将generateRequest()更改为GenerateRequest(),并确保在GenerateRequest()包中定义goClientLib功能。查看this以获取更多信息。