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

Susan Sarandon
Release: 2024-10-26 07:56:30
Original
347 people have browsed it

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>
Copy after login

you can write:

<code class="go">import . "fmt"</code>
Copy after login

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>
Copy after login

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>
Copy after login

Playground

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

Output:

Hello, world
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!