46 lines
963 B
Markdown
46 lines
963 B
Markdown
---
|
||
paths:
|
||
- "**/*.go"
|
||
- "**/go.mod"
|
||
- "**/go.sum"
|
||
---
|
||
# Go 模式 (Patterns)
|
||
|
||
> 本檔案擴展了 [common/patterns.md](../common/patterns.md),包含 Go 特定內容。
|
||
|
||
## 函式選項模式 (Functional Options)
|
||
|
||
```go
|
||
type Option func(*Server)
|
||
|
||
func WithPort(port int) Option {
|
||
return func(s *Server) { s.port = port }
|
||
}
|
||
|
||
func NewServer(opts ...Option) *Server {
|
||
s := &Server{port: 8080}
|
||
for _, opt := range opts {
|
||
opt(s)
|
||
}
|
||
return s
|
||
}
|
||
```
|
||
|
||
## 精簡介面 (Small Interfaces)
|
||
|
||
在「使用」介面的地方定義介面,而非在「實作」介面的地方定義。
|
||
|
||
## 依賴注入 (Dependency Injection)
|
||
|
||
使用建構函式來注入依賴:
|
||
|
||
```go
|
||
func NewUserService(repo UserRepository, logger Logger) *UserService {
|
||
return &UserService{repo: repo, logger: logger}
|
||
}
|
||
```
|
||
|
||
## 參考資源
|
||
|
||
參見技能 (Skill):`golang-patterns`,獲取包含併發 (Concurrency)、錯誤處理與包組織的全面 Go 模式。
|