首頁 > 後端開發 > Golang > 如何在 Go 中使用不同套件中的類型?

如何在 Go 中使用不同套件中的類型?

DDD
發布: 2024-11-15 09:07:02
原創
814 人瀏覽過

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
登入後複製

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"
)
登入後複製

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.

以上是如何在 Go 中使用不同套件中的類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板