SoFunction
Updated on 2025-03-05

Several ways to import packages in Golang (dots, alias and underscores)

1. Import of packages

When Golang imports multiple packages, the package names are usually arranged alphabetically. IDEs such as Goland will automatically complete this action when saving files.
Golang import package is equivalent to all code objects containing this package.
To avoid name conflicts, the identifiers of all objects in the same package must be unique. But the same identifier can be used in different packages, because the package name can be used to distinguish them.

2. Different import methods of packages

1. Import a single

The code is as follows (example):

package main
import "context" //Load the context package

2. Import multiple packages

The code is as follows (example):

import (
    "context"
    "fmt"
    "net/http"
)

General way of calling:

("Go Go Go")

3. Special import method

1. Point (.) operation

The code is as follows (example):

import ( 
    . "fmt" 
    )

Println(“Hello World!”)

The meaning of point operation is that after a package is imported, the prefixed package name can be omitted when calling the function of this package.
fmt package can ignore fmt
Time package can also be omitted

2. Alias ​​operation
The code is as follows (example):

import (
    f "fmt"
)

(“Hello World!”)

The alias operation is to name the package as another easy-to-memorize name.

ps: This is sometimes used in actual projects, but please use it with caution.

3. Underline (_) Operation

The code is as follows (example):

import (
    _ "fmt"
    _ "/go-sql-driver/mysql"
)

Introduce a package, but do not use the functions in the package directly, but call the init function in the package, such as the import of the following mysql package.
ps: In addition, in development, for some reason, a package imported from the original is no longer used, and this method can also be processed.

Summarize

The purpose of using packages is to manage source code more conveniently. Golang's philosophy is to use folders to manage (or constraints) the source code of the same type or the same function. Different package import methods play different roles in work, and we need to learn and use them flexibly. This will be some methods that we will always use in the process of learning Golang.

This is the end of this article about several ways to import the Golang package (dots, alias and underscores). For more related contents of Golang import package, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!