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
vi service.go
package simple
import "fmt"
func Do(){
fmt.Println("Do")
}
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?
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
So we move main in its own directory.
mkdir main
mv main.go main
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()
}
go run main/main.go
Output:
Main
Do
Now it is working!
Good job guys :)
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.
See the full source on github.