![]() |
VOOZH | about |
We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.
Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.
Follow TNS on your favorite social media networks.
Become a TNS follower on LinkedIn.
Check out the latest featured and trending stories while you wait for your first TNS newsletter.
package main
import "fmt"
func main() {
fmt.Println("Hello, New Stack")
}
nano quote.go
In that file, paste the following:
package main
import "fmt"
import "rsc.io/quote"
func main() {
fmt.Println("Your pithy quote of the day is:\n")
fmt.Println(quote.Go())
}
go mod init quote
Once you’ve done that, you can then download the package with:
go mod tidy
Now, compile your application with:
go build quote.go
This will create an executable named call. Run the app with:
./quote
You’ll see the output I listed above.
Let’s go a bit deeper.
What we’re going to do now is create our own module and then call it from an application.
First, create a new directory structure with the command:
mkdir -p projects/mymodule
Change into the modules directory with:
cd projects/mymodule
Initialize modules with:
go mod init mymodule
You’ll find a new go.mod file has been added.
Next, create a main.go file with:
nano main.go
In that file, paste the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, New Stack!")
}
go run main.go
You should see the following output:
Hello, New Stack!
Great.
Now, we’re going to create a new package that we’ll then call from our main.go file. Still, in the mymodule directory, create a new directory with:
mkdir mypackage
Create a new .go file with:
nano mypackage/mypackage.go
In that file, paste the following:
package newpackage
import "fmt"
func NSHello() {
fmt.Println("Hello, New Stack! You've just called your first module!")
}
nano /main.go
Currently, the file looks like this:
package main
import "fmt"
func main() {
fmt.Println("Hello, New Stack!")
}
import ( "fmt" "mymodule/mypackage" )
func main() {
fmt.Println("Hello, New Stack!")
mypackage.NSHello()
}
package main
import (
"fmt"
"mymodule/mypackage"
)
func main() {
fmt.Println("Hello, New Stack!")
mypackage.PrintHello()
}
go run main.go
The output should be:
Hello, New Stack!
Hello, New Stack! You’ve just called your first module!
Or, you can build an executable with the command:
go build main.go
And that is your introduction to calling external packages in Golang.