How to use packages without Github?

I am trying to understand the use of packages, but get errors when building. There are lots of threads out there, but they focus on github and I cannot translate this to a simple task like this.

package main
import "fmt"
func main() {
    fmt.Printf("hello, cruel world\n")
}

This works, but when moving the print to another package.

/src/main/main.go

package main
import "pkg/print"
func main() {
    print.Hello
}

/src/pkg/print.go

package print
import "fmt"
func Hello() {
    fmt.Printf("hello, cruel world\n")
}

cannot find package “pkg/print” in any of:
/usr/local/go/src/pkg/print (from $GOROOT)
/Users/sibert/go/src/pkg/print (from $GOPATH)

What am I doing wrong? The path is correct.

1 Like

Hi Sibert

A few things as I understand.

  • First of all, src folder is where you will have all your projects. So its better you create a folder first inside src for your project and then create main and pkg inside it.

  • Second, it’s a protocol to give package name and parent folder name as the same. Since you have package name as print, give folder name as print instead of pkg. That way you can import “project folder/print” in main.go

  • And unlike languages like scala, you cant give print.Hello : Even without arguments it should be print.Hello() with empty parenthesis.

Like this :

->src 
   -> abc (your project folder)
        -> main
             -> main.go
        -> print (notice that I changed it from pkg)
             -> print.go

Your main.go will be like this now:

package main
import "abc/print"    // import path from project folder
func main() {
    print.Hello()    // added empty parenthesis
}

Hope this helps!

3 Likes

Thank you! It worked!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.