Home >Backend Development >Golang >Go Package Structure: Do We Need a `package.go` File, How to Import Internal Files, and Can We Access Types Across Files?

Go Package Structure: Do We Need a `package.go` File, How to Import Internal Files, and Can We Access Types Across Files?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 04:04:08494browse

Go Package Structure: Do We Need a `package.go` File, How to Import Internal Files, and Can We Access Types Across Files?

Go Language Package Structure: An in-Depth Explanation

When working with Go, adhering to established conventions is crucial. However, understanding these conventions is paramount before their effective implementation. This article tackles a frequently asked question regarding Go's package structure.

Question

Setup: Following the recommended project structure, we have:

$GOPATH/
  src/
    github.com/
      username/
        projectname/
          main.go
          numbers/
            rational.go
            real.go
            complex.go

main.go:

package main

import (
  "fmt"
  "./numbers"
)

func main() {
  fmt.Println(numbers.Real{2.0})
}

Questions:

  • Do we require a package.go file in each package folder?
  • How do we import files within the same package in numbers.go?
  • Can we define types like Real in real.go and access them in main.go as fmt.Println(numbers.Real{2.0})?

Answer

1. package.go File

The assumption that every package directory requires a package.go file is incorrect. In Go, files within a single directory are automatically grouped into a package. Creating a package.go file is unnecessary.

2. Importing Files Within a Package

Go does not support importing files. Package numbers should be imported directly, rather than individual files like rational.go, real.go, and complex.go. In our example, remove the ./ prefix and use import "github.com/username/projectname/numbers".

3. Sharing Types

Types like Real should be defined in a file within the package, such as real.go. As the files belong to the same package, no additional import statement is needed. Accessing the Real type in main.go as fmt.Println(numbers.Real{2.0}) is correct.

The above is the detailed content of Go Package Structure: Do We Need a `package.go` File, How to Import Internal Files, and Can We Access Types Across Files?. 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