Home >Backend Development >Golang >How do I import the entire contents of a Go package?

How do I import the entire contents of a Go package?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 07:56:30429browse

How do I import the entire contents of a Go package?

Importing the Entire Contents of a Go Package

In Go, you can import individual functions, variables, or types from a package. However, you can also import the entire contents of a package, eliminating the need to prefix calls to its members with the package name.

The Dot Import

The Go Programming Language Specification allows for a dot import, represented by a period (.). When used in an import declaration, it instructs the compiler to import all exported identifiers from the specified package.

Usage

To import the full contents of a package, replace the package name with a period in the import declaration. For example, instead of:

<code class="go">import "fmt"</code>

you can write:

<code class="go">import . "fmt"</code>

Access Imported Members

Once imported, the exported members of the package become accessible without the package prefix. For example:

<code class="go">package main

import . "fmt"

func main() {
    Println("Hello, world")
}</code>

This code is equivalent to the following, where each call is prefixed with the fmt package name:

<code class="go">package main

import "fmt"

func main() {
    fmt.Println("Hello, world")
}</code>

Playground

You can experiment with this feature in the Go Playground: https://play.golang.org/p/xl7DIxxMlU5

Output:

Hello, world

The above is the detailed content of How do I import the entire contents of a Go package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn