In the previous chapter, we simply created a module and simply defined a function. Now we continue to complete the module creation.
The code
Before writing, make sure that the greetings module we created earlier already exists. This is the Greetings module we created in the previous chapter.
- Create another directory
hello
You need to keep upgreetings
Modules remain at the same level.├── greetings └── hello Copy the code
- Continue to track the current module dependency changes using the module trace command.
go mod init montos.com/hello Copy the code
- Carry out our
hello.go
Code writing.package main import ( "fmt" "montos.com/greetings" ) func main(a) { // Get a greeting message and print it. message := greetings.Hello("Gladys") fmt.Println(message) } Copy the code
Here’s a quick analysis of what the code does:
- First declare the package as
main
The package. (Go
The run code entry must be declared inmain
In the package) - Import two packages:
fmt
As well asmontos.com/greetings
, followed by a package we created ourselves in the previous section, which is referenced here. - By calling the
greetings
The function in the package gold is the execution of the local method.
- First declare the package as
- Edit local
hello
The module uses localgreetings
The module.
In the case of production use, we are releasing modules to our private repository, and in this demonstration we are directly using local modules.
- Run the following command at a command prompt in the Hello directory:
gomod edit -replace=montos.com/greetings=.. /greetingsCopy the code
Using this command is to specify that the imported package in the code is replaced by our native package. 2. Run commands to synchronize the current dependencies.
[root@montos-prod hello]# go mod tidy go: found montos.com/greetings in montos.com/greetings v0. 0. 0- 00010101000000.- 000000000000. Copy the code
- Finally, run the current code environment.
[root@montos-prod hello]# go run .
Hi, Gladys. Welcome!
Copy the code
conclusion
At this point, we have completed a simple dependency module function call. The function is called through local module import dependencies. Simply running a function, the next section will show you how to handle errors in Go and return them in a friendly way.