Adding Packages

Add a package

As we named the package “simple”, we now create some files which uses this package which is named like the module:

From:

.
├── go.mod
└── main.go

We

  1. Add a service file
vi service.go
package simple

import "fmt"

func Do(){
  fmt.Println("Do")
}
  1. Update Main to use the “Do” service:
package main

import (
	"fmt"
	"simple"
)

func main() {
	fmt.Println("Main")
	Do()
}

To use the “Do” function, which is be definition exported, because it starts with an uppercase “D”, the import sections has to import “simple”.

What will now happen if we run?

Run

go run main.go

We get an error:

main.go:5:2: found packages main (main.go) and simple (service.go) in ...(your directory path)

One directory can only contain one package

Separate packages

So we move main in its own directory.

  1. mkdir main
  2. mv main.go main

Run

go run main/main.go

And again we get an error:

# command-line-arguments
main/main.go:5:2: imported and not used: "simple"
main/main.go:10:2: undefined: Do

To use the exported function “Do” from the imported package “simple”, we have to call:

simple.Do()

So main/main.go should be

package main

import (
	"fmt"
	"simple"
)

func main() {
	fmt.Println("Main")
	simple.Do()
}

Run

go run main/main.go

Output:

Main
Do

Now it is working!

Good job guys :)

Import external modules

Until now we have used the basic modules like “fmt”.

Most IDEs like VSCode give you a link to the documentation of the module. If you hover the mouse over “fmt”, you get the link! fmt

But how do we import external modules? Lets see in the next chapter.

Source

See the full source on github.

Sources