Golang : The Tao of importing package
Jotting down this quick tutorial on how to use import
statement properly with formatted I/O - fmt package. However, this example can be applied to all Golang packages. Hope this simple tutorial can be useful to you too.
The standard way to import package in Golang.
import "fmt"
package main
import "fmt"
func main() {
fmt.Println("Hello, playground")
}
In case, you want to name the package name differently or want to use a shorter name to invoke the package.
import
ftio
"fmt"
package main
import ftio "fmt"
func main() {
ftio.Println("Hello, playground")
}
If the program is a short and simple program. Use a period .
to represent a package. Useful in a situation where there are a lot of invocation of the package functions. However, this might cause readability issue later on...so use it with care.
import
.
"fmt"
package main
import . "fmt"
func main() {
Println("Hello, playground")
}
Lastly, the underscore _
is used in import statement to initialize a package. Without the underscore _
, you will get imported but not used error message
import
_
"fmt" -- initialize for other function to use.
package main
import _ "fmt"
func main() {
Println("Hello, playground") // will cause prog.go:6: undefined: Println error
}
a common example to use underscore is to initialize the mysql
driver in order to the sql.Open()
function to use the mysql
driver. See full example at :
https://www.socketloop.com/tutorials/golang-connect-to-database-mysql-mariadb-server
Happy Coding!
Reference:
https://www.socketloop.com/tutorials/golang-shortening-import-identifier
See also : Golang : Connect to database (MySQL/MariaDB) server
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+36.4k Golang : Convert date or time stamp from string to time.Time type
+9.3k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+7.4k Golang : How to fix html/template : "somefile" is undefined error?
+14.6k Golang : Execute function at intervals or after some delay
+8.2k Golang : Routes multiplexer routing example with regular expression control
+27k Golang : Force your program to run with root permissions
+15.6k Golang : How to convert(cast) IP address to string?
+9.3k Golang : does not implement flag.Value (missing Set method)
+12.8k Golang : Add ASCII art to command line application launching process
+30.9k error: trying to remove "yum", which is protected
+11.3k CodeIgniter : How to check if a session exist in PHP?
+28.3k Golang : Connect to database (MySQL/MariaDB) server