Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Idiomatic Code Organization | Packages, Modules, and Generics
Practice
Projects
Quizzes & Challenges
Вікторини
Challenges
/
Advanced Go

bookIdiomatic Code Organization

Свайпніть щоб показати меню

Go Project Structure

Organize your Go projects using the following structure for clarity and maintainability:

  • Place the main entry point in a cmd/ directory;
  • Store application code in an internal/ directory for private packages;
  • Keep reusable packages in a pkg/ directory;
  • Group configuration files and assets in a configs/ or assets/ directory;
  • Place third-party dependencies in a vendor/ directory if vendoring is required.

A typical layout:

myapp/
├── cmd/
│   └── myapp/
│       └── main.go
├── internal/
│   └── service/
│       └── service.go
├── pkg/
│   └── utils/
│       └── utils.go
├── configs/
├── assets/
├── go.mod
└── go.sum

File Organization and Naming

  • Use one package per directory; name the directory after the package;
  • Name files to reflect their purpose, such as http.go, db.go, or service.go;
  • Keep related types and functions together for discoverability;
  • Avoid stutter by matching package and type names (e.g., user.User is redundant, prefer user.Model).

Package Design Principles

  • Keep packages focused on a single responsibility;
  • Expose only what is necessary: use lowercase for unexported identifiers and uppercase for exported ones;
  • Avoid circular dependencies between packages;
  • Document packages and exported functions using Go doc comments.

Best Practices for Clean Code

  • Write short, focused functions;
  • Use clear, descriptive names for variables and functions;
  • Prefer composition over inheritance;
  • Handle errors explicitly and consistently;
  • Write tests alongside your code in *_test.go files.

Following these conventions makes your Go projects easier to understand, test, and maintain as they grow.

question mark

Which approach best reflects idiomatic Go code organization?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 2. Розділ 4
some-alt