Home > Backend Development > Golang > How to Use Types from Different Packages in Go?

How to Use Types from Different Packages in Go?

DDD
Release: 2024-11-15 09:07:02
Original
815 people have browsed it

How to Use Types from Different Packages in Go?

Importing Packages and Types

In Go, a common issue arises when attempting to import a type from a different package. This problem is highlighted by the following code structure:

src
|-->config
       |--> config.go
|-->otherPackage
       |--> otherFile.go
|-->main.go
Copy after login

The goal is to use a type declared in config.go within the otherFile.go file. However, importing config within otherFile.go leads to errors such as "imported and not used" and "undefined: Config."

Go does not support importing specific types from a package. Instead, you must import the entire package, thus qualifying any type references with the package name, like so:

import (
    "fmt"
    "math"
    "./config"
)
Copy after login

Using this import statement, you can reference the type Config from config.go using the fully qualified name config.Config. Alternatively, to prevent shadowing, you can:

  1. Rename the config variable to something else (e.g., cfg).
  2. Reference Config using its qualified name, config.Config.

The above is the detailed content of How to Use Types from Different Packages in Go?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template