-2

I am attempting to do a local import but it fails.

My environment is:

echo $GOPATH /home/peter/go echo $GOROOT /usr/local/go

The entry point is:

/home/peter/go/src/projects/pkgs1/main.go

The imported file is:

/home/peter/go/src/projects/pkgs2/stuff.go

main.go

package main

import (
    "fmt"
    "projects/pkgs2"  // <- this does not resolve
)

func main(){
    fmt.Println("123")
    pkgs2.X()
}

stuff.go

package pkgs2

import "fmt"

func X(){
    fmt.Println("X")
}

Any pointers on what I do wrong?

pigfox
  • 1,301
  • 3
  • 28
  • 52
  • 1
    What does `but it fails` mean? What does the compiler say?` – tkausl Aug 21 '19 at 08:12
  • The compiler says cannot resolve "projects" which is in the src folder ~/go/src/projects/pkgs2$ pwd /home/peter/go/src/projects/pkgs2 – pigfox Aug 21 '19 at 08:26
  • FYI: (1) `x` is unexported so you won't be able to call it even if your import worked. (2) The call `x()` is unqualified, to reference an imported identifier you have to qualify it by prepending the package name, just like you're doing with `fmt.Println` by prepending the package name `fmt` to the identifier `Println`. So *export* your identifiers and then *qualify* them if you use them. – mkopriva Aug 21 '19 at 08:36
  • have you tried giving the complete path from home? – Barkha Aug 21 '19 at 08:36
  • 1
    @user8351493 that's not how Go's `import` statements work. – Dave C Aug 21 '19 at 16:46

1 Answers1

2

Your import path is correct and should resolve successfully, but as written, your program won't compile because the import isn't being used and there is no local function named x.

As mentioned by mkopriva your x function in pkgs2 isn't exported and you have not qualified it when trying to use it in your main package.

To export a function, it needs to start with a capital letter.

To use the function in another package, you need to prefix the package name to the function name.

main.go

package main

import (
    "fmt"
    "projects/pkgs2"
)

func main(){
    fmt.Println("123")
    pkgs2.X()
}

stuff.go

package pkgs2

import "fmt"

func X(){
    fmt.Println("X")
}
PassKit
  • 12,231
  • 5
  • 57
  • 75
  • The code is modified for export of X(), see above. I also tried the absolute path which was not allowed. The error remains: "Cannot resolve directory projects". – pigfox Aug 21 '19 at 09:05
  • 2
    How are you compiling/running this? Are you using an IDE? Some IDE's run in a shell with independent environment variables. What if you cd into you pkgs1 folder and type `GOPATH=/home/peter/go/ go run main.go`? – PassKit Aug 21 '19 at 09:08
  • Thank you for pointing that out. I use Jetbrains Goland. After I cd into pkgs1 folder and type GOPATH=/home/peter/go/ go run main.go it works as expected. – pigfox Aug 21 '19 at 09:28
  • In goland you need to set the GOPATH in preferences->go. You can set the GOROOT too, although that’s optional. – PassKit Aug 21 '19 at 09:31