To import more than one package in Go or Golang, you need to write the import
keyword followed by the ()
symbol (opening and closing brackets), and inside the brackets, you can write the name of the package in ""
symbol (double quotation) separated by the space.
TL;DR
package main
// import the `time` and `fmt` package
import (
"fmt"
"time"
)
func main() {
// get the current time
// and store it in a variable
currentTime := time.Now()
// show the current time to
// the user in the console
fmt.Println(currentTime)
}
For example, let's say we need to show the current time to the user. To do that first we need to import 2 packages namely time
and fmt
.
The fmt
package is used to show the output written to the console and the time
package is used to work with time.
First, let's import the 2 packages.
It can be done like this,
package main
// import the `time` and `fmt` package
import (
"time"
"fmt"
)
Now let's use the Now()
method from the time
package to get the current time and store it in a variable like this,
package main
// import the `time` and `fmt` package
import (
"time"
"fmt"
)
func main(){
// get the current time
// and store it in a variable
currentTime := time.Now()
}
Finally, let's show the current time to the user in the console using the Println()
method from the fmt
package.
it can be done like this,
package main
// import the `time` and `fmt` package
import (
"fmt"
"time"
)
func main() {
// get the current time
// and store it in a variable
currentTime := time.Now()
// show the current time to
// the user in the console
fmt.Println(currentTime)
}
We have successfully imported more than one package in Golang. Yay 🥳.
See the above code live in The Go Playground.
That's all 😃!
Top comments (0)