Go organizes code into packages. Each .go file must declare the package it belongs to. A package is a directory containing one or more .go files. A module is a collection of packages managed by a go.mod file. Modules allow you to manage dependency versions and share code.
Go tổ chức code thành package (gói). Mỗi file .go phải khai báo package nó thuộc về. Một package là một thư mục chứa một hoặc nhiều file .go. Module là một tập hợp các package được quản lý bởi go.mod file. Module cho phép bạn quản lý phiên bản phụ thuộc (dependency) và chia sẻ code.
package main is special -> it defines an executable program with a main() function. All other packages are libraries. The package name usually matches the directory name. Packages are the basis of encapsulation and reuse in Go.
Package main là đặc biệt - nó định nghĩa một chương trình thực thi với hàm main(). Tất cả các package khác là library. Tên package thường khớp với tên thư mục. Package là cơ sở của encapsulation và reuse trong Go.
1// math/math.go2package math34// Package level constants5const Pi = 3.1415967// Package level variables8var counter int910// Unexported function (lowercase)11func add(a, b int) int {12 return a + bGo has no public/private keywords. Instead, it uses naming conventions. Names starting with an uppercase letter are exported (public). Names starting with a lowercase letter are unexported (private). This applies to functions, types, variables, constants, and methods.
Go không có public/private keyword. Thay vào đó, nó sử dụng chuỗi casing (case rule). Tên bắt đầu với chữ cái in hoa (uppercase) được exported (công khai). Tên bắt đầu với chữ cái thường (lowercase) được unexported (private). Điều này áp dụng cho hàm, type, biến, hằng số, và method.
1package user23// Exported type (can be imported and used elsewhere)4type User struct {5 Name string // Exported field6 Email string // Exported field7 age int // Unexported field8}910// Exported function11func NewUser(name, email string, age int) *User {12 return &User{Use the import statement to use code from other packages. You can import one package, multiple packages at once, or use aliases. Blank import _ "pkg" is for side effects (e.g., database drivers). Dot import (.) is not recommended as it reduces clarity.
Sử dụng import statement để sử dụng code từ package khác. Bạn có thể import một package, multiple package cùng một lúc, hoặc sử dụng alias. Blank import _ 'pkg' dùng cho side effects (ví dụ, database drivers). Dot import (.) không được khuyến nghị vì nó làm mất rõ ràng nguồn.
1package main23import (4 // Single import5 "fmt"67 // Alias import8 m "math"910 // Local package import11 "mymodule/user"12The go.mod file defines your module and its dependencies. It contains the module path (name), Go version, and require directives. The go.sum file is a lockfile containing checksums of each dependency version. go mod tidy downloads necessary dependencies and removes unused ones.
go.mod file định nghĩa module của bạn và các dependency. Nó chứa module path (tên module), Go version, và require directives (phụ thuộc). go.sum file là lockfile chứa checksum của mỗi dependency version. go mod tidy tải các dependency cần thiết và xóa các không dùng.
1// go.mod example2module github.com/alice/myapp34go 1.2156require (7 github.com/gin-gonic/gin v1.9.18 github.com/lib/pq v1.10.99)1011require (12 github.com/google/uuid v1.3.0 // indirect (transitive dependency)go get downloads a package and its dependencies, updating go.mod. go get ./... downloads all dependencies of the current project. go install builds and installs a binary executable to $GOBIN. go install tool@latest installs the latest version of a tool.
go get tải một package và các dependency của nó, cập nhật go.mod. go get ./... tải tất cả dependency của project hiện tại. go install xây dựng và cài đặt một binary executable vào $GOBIN. go install tool@latest cài đặt phiên bản mới nhất của một tool.
1// Terminal commands23// Add a dependency4go get github.com/lib/pq56// Add a specific version7go get github.com/lib/pq@v1.10.989// Remove a dependency (use go get and then tidy)10go get github.com/lib/pq@none11go mod tidy12Place packages in an internal/ directory to restrict who can import it. Only packages in the parent module can import from internal/. This is a good way to encapsulate implementation details that should not be public.
Đặt package vào thư mục internal/ để giới hạn ai có thể import nó. Chỉ package trong parent module mới có thể import từ internal/. Đây là cách tốt để đóng gói các chi tiết triển khai không nên được công khai.
1// Project structure:2// mymodule/3// ├── go.mod4// ├── main.go5// ├── api/6// │ └── handler.go7// └── internal/8// └── database/9// └── db.go1011// internal/database/db.go12package databasego work allows you to work with multiple modules at once. Create a go.work file listing local modules. This is useful when developing related modules, such as a backend and shared library.
go work cho phép làm việc với nhiều module cùng một lúc. Tạo go.work file để liệt kê các module cục bộ. Điều này hữu ích khi phát triển nhiều module liên quan, chẳng hạn như backend và shared library.
1// go.work2go 1.2134use (5 ./backend // Local module6 ./shared // Local module7 ./cli-tool // Local module8)910// Terminal:11// go work init ./backend ./shared # Create go.work12// go work use ./cli-tool # Add another module13// go work edit -dropuse=./cli-tool # Remove a module1415// When using go.work, local modules are used instead of go.mod versions16// This allows testing changes across multiple modules before publishinggo mod tidy nên được chạy thường xuyên để giữ go.mod và go.sum sạch sẽ. Luôn commit go.sum vào version control để đảm bảo tính nhất quán của build.
Key Takeaways
Điểm Chính
- Uppercase names are exported, lowercase names are unexportedTên uppercase được export, tên lowercase không được export
- go.mod defines module path and dependenciesgo.mod định nghĩa đường dẫn module và phụ thuộc
- internal/ directory restricts imports to the same moduleThư mục internal/ giới hạn import cho cùng một module
- go get downloads dependencies, go install builds executablesgo get tải phụ thuộc, go install xây dựng các file thực thi
Practice
Test your understanding of this chapter
Which naming convention makes a function accessible from other packages?
Quy ước đặt tên nào làm cho một hàm có thể truy cập từ các package khác?
What is the purpose of go.sum file?
Tập tin go.sum có mục đích gì?
You can import from the internal/ directory of other modules in your go.get dependencies.
Bạn có thể import từ thư mục internal/ của các module khác trong các phụ thuộc go.get.
Running go mod tidy will remove dependencies from go.mod that are no longer used in the code.
Chạy go mod tidy sẽ xóa các phụ thuộc từ go.mod mà không còn được sử dụng trong code.
Add a package to your module
Thêm một package vào module của bạn
go github.com/goreleaser/goreleaser