GO · 패턴
Functional Options 패턴
Go에서 선택적 설정을 우아하게 처리하는 대표적인 패턴입니다.
패턴중급functional-optionsoptionbuilderAPI-designvariadic
핵심 설명
Go에서 선택적 설정을 우아하게 처리하는 대표적인 패턴입니다.
Go code
package main
import (
"fmt"
"time"
)
type Server struct {
host string
port int
timeout time.Duration
maxConn int
}
// Option 타입 — 함수로 설정 주입
type Option func(*Server)
func WithHost(host string) Option {
return func(s *Server) { s.host = host }
}
func WithPort(port int) Option {
return func(s *Server) { s.port = port }
}
func WithTimeout(d time.Duration) Option {
return func(s *Server) { s.timeout = d }
}
func WithMaxConn(n int) Option {
return func(s *Server) { s.maxConn = n }
}
// 기본값 + 옵션 오버라이드
func NewServer(opts ...Option) *Server {
s := &Server{
host: "localhost",
port: 8080,
timeout: 30 * time.Second,
maxConn: 100,
}
for _, opt := range opts { opt(s) }
return s
}
func (s *Server) String() string {
return fmt.Sprintf("Server{%s:%d, timeout:%v, maxConn:%d}",
s.host, s.port, s.timeout, s.maxConn)
}
func main() {
// 기본값만 사용
s1 := NewServer()
fmt.Println(s1)
// 일부만 오버라이드
s2 := NewServer(
WithHost("0.0.0.0"),
WithPort(9090),
WithTimeout(60*time.Second),
)
fmt.Println(s2)
// 모두 오버라이드
s3 := NewServer(
WithHost("api.example.com"),
WithPort(443),
WithMaxConn(1000),
)
fmt.Println(s3)
}학습 팁
Functional Options 패턴은 하위 호환성을 유지하면서 새 옵션을 추가하기 쉽습니다. 라이브러리 API 설계에 특히 유용합니다.
주의할 점
구조체에 공개 필드를 그냥 두면 제약 조건을 걸기 어렵습니다. Functional Options로 유효성 검사를 Option 함수 안에 넣을 수 있습니다.
자주 묻는 질문
Functional Options 패턴란 무엇인가요?
Go에서 선택적 설정을 우아하게 처리하는 대표적인 패턴입니다.
Functional Options 패턴 학습 시 주의할 점은 무엇인가요?
구조체에 공개 필드를 그냥 두면 제약 조건을 걸기 어렵습니다. Functional Options로 유효성 검사를 Option 함수 안에 넣을 수 있습니다.
Continue Learning
Go 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.