Tuesday, 24 December 2024

GO folder and package naming and best practices

 Best Practice

  • Best Practice: Keep the package name the same as the folder name for clarity and consistency.
  • Multiple Files: All .go files in the same folder must declare the same package name.
  • Internal Packages: For internal use, you can place packages inside an internal/ folder to restrict visibility.

  • Example 1: Matching Folder and Package Name

    Directory structure:

    css

    project/ ├── mypackage/ │ ├── mypackage.go └── src/ └── main.go

    mypackage.go:

    go

    package mypackage import "fmt" func Hello() { fmt.Println("Hello from mypackage!") }

    main.go:

    go

    package main import ( "project/mypackage" ) func main() { mypackage.Hello() }
  • ----------------------------

  • Example 2: Different File Names but Same Package

    Directory structure:


    project/ ├── mypackage/ │ ├── file1.go │ ├── file2.go └── src/ └── main.go

    file1.go:


    package mypackage func Hello() string { return "Hello" }

    file2.go:


    package mypackage func World() string { return "World" }

    main.go:


    package main import ( "project/mypackage" "fmt" ) func main() { fmt.Println(mypackage.Hello(), mypackage.World()) }

  • --------------------------------------------------
  • No, the package name does not have to be the same as the folder name, though it is a widely followed convention in Go. Here's a detailed explanation:


    Package Name vs. Folder Name

    1. Folder Name:

      • The folder name is part of the import path.
      • For example, if the folder is named mypackage, you would import it as:
        go
        import "project/mypackage"
    2. Package Name:

      • The package name is defined by the package keyword in the .go files within that folder.
      • It determines how you reference the package's exported functions, variables, or types in your code.
      • The package name does not need to match the folder name.

    When Package Name and Folder Name Differ (NOT REOMMENDED)

    You can have a folder with one name and a different package name. For example:

    Directory structure:

    css
    project/ ├── utils/ │ ├── math.go └── src/ └── main.go

    math.go (in the utils/ folder):

    go
    package mathutils func Add(a, b int) int { return a + b }

    main.go:

    go
    package main import ( "project/utils/mathutils" "fmt" ) func main() { fmt.Println(mathutils.Add(2, 3)) // Output: 5
  • No comments:

    Post a Comment