Go run/build cannot find source files

3therk1ll :

I am trying to run a simple hello world style program that imports a print function from a separate custom package but Go is unable to find it despite teh correct $GOPATH etc being set.

What is missing that will make teh file be picked up?

etherk1ll@ubuntu:~/Development/GoWorkSpace/src/sonarparser$ echo $GOPATH 
/home/etherk1ll/Development/GoWorkSpace/
etherk1ll@ubuntu:~/Development/GoWorkSpace/src/sonarparser$ pwd
/home/etherk1ll/Development/GoWorkSpace/src/sonarparser
etherk1ll@ubuntu:~/Development/GoWorkSpace/src/sonarparser$ ls
jsonparser.go  main.go
etherk1ll@ubuntu:~/Development/GoWorkSpace/src/sonarparser$ go run main.go 
main.go:5:2: cannot find package "sonarparser/jsonparser" in any of:
    /usr/local/go/src/sonarparser/jsonparser (from $GOROOT)
    /home/etherk1ll/Development/GoWorkSpace/src/sonarparser/jsonparser (from $GOPATH)

main.go

package main

import (
    "fmt"
    "jsonparser"
)

func main() {
    fmt.Println("Hello world 1")
    fmt.Println(jsonparser.HelloTwo)
}

jsonparser.go

package jsonparser

import "fmt"

func HelloTwo() {
    fmt.Println("Hello world 2")
}
hqt :

Because jsonparser.go and main.go are in the same package, Go requires those files to have the same package name. And because you defined the main function for the execution, the package must be "main".

Step 1: So you should rename jsonparser.go's package to main.

// jsonparser.go
package main

import "fmt"

func HelloTwo() {
    fmt.Println("Hello world 2")
}

Step 2: You need to update main.go file to correct the import path:

// main.go
package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello world 1")
    HelloTwo()
}

Step 3: Then you run the following command (you must include all necessary files in the command)

go run main.go jsonparser.go

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=410683&siteId=1