1. 범위(Scope)
이 실천 방법들은 Go 1.27 언어 시맨틱, 런타임 기본값, 기본 실험 구성을 가정합니다.
2. 개념 파일로의 경로(Route to concept files)
범위 내 코드와 작업에 따라 경로를 정하고, 변경 또는 diff의 경우 변경된 코드에 집중합니다. 인덱스는 주제와 예시 코드 패턴을 결합합니다. X, T, x, v는 임의의 이름을 나타냅니다. 아래 추가 경로를 포함하여 일치하는 모든 참조를 엽니다.
해당 heading의 ID 접두사로 실천 방법을 찾고 전체 ID를 인용합니다. Practice를 따르고, Example을 관용구로 사용하며, Why, Exceptions, Tradeoff를 통해 메커니즘, 적용 가능성 및 비용을 확인합니다. Signals는 누락된 실천 방법을 식별합니다.
또한 누락된 보호 장치나 증상에 대해 다음 참조를 엽니다.
- 모듈 또는 파일 언어 버전 불일치, 빌드 제약 조건, 런타임 동작 재정의: MOD.
error를 확인하거나 버리는 코드: ERH.- 고루틴 또는 채널: CTX, GOR, SHR.
- 블로킹 I/O (네트워크, 데이터베이스, HTTP, 파일) 또는 HTTP 핸들러: CTX.
- 동시성 코드 테스트: TBA, TST.
- 증가하는 메모리 또는 고루틴 수: PRO, MRT.
- 높은 GC CPU, 또는 컨테이너 내 프로그램: BRT, PRO, TRC.
- 핫 경로(hot path), 또는 코드 속도 향상 요청: PRO, ALO, BEN.
2.1 언어(Language)
- CST code-structure.md: 섀도잉(shadowing), 패키지/내장 이름 (
url,len,new,max), 조기 반환 (return 이후의else),func init(). - STD struct-design.md: getter/setter (
GetX/SetX), 임베딩 (sync.Mutex), 승격된 필드 리터럴, 함수형 옵션 (NewXWithY,Config인자),new(expr)및 포인터 헬퍼 (ptr[T],intPtr). - INT interfaces.md: 인터페이스 생성/소유권, 단일 구현 인터페이스, 구체 타입 vs 인터페이스 결과,
any/interface{}, 타입이 nil인 인터페이스/에러. - GEN generics.md: 타입 파라미터 (
[T any]), 제약 조건 (comparable,~int,~string,cmp.Ordered,golang.org/x/exp/constraints), 추론, 제네릭 메서드, 자기 참조 제약 조건. - FNM functions-and-methods.md: 값/포인터 또는 혼합 리시버, 뮤텍스를 포함한 값 리시버, 이름 있는 반환값 (
n int, err error), naked return. - LOP loops.md: range 복사 (
v.field =), 표현식 평가, 반복별 변수 (v := v,&v, 고루틴 클로저),range n,for i := 0; i <,slices.Backward, 레이블 break,switch/select내break. - ITR iterators.md: 이터레이터 소비/생성,
iter.Seq/iter.Seq2(파라미터 포함),yield,iter.Pull,Next()/Value(), 모든 요소를 슬라이스로 반환하는 메서드,slices.Collect. - DEF defer-and-cleanup.md: 루프 내
defer, 지연된 인자/리시버 평가,io.Closer정리 (defer f.Close(),resp.Body,rows.Close()),Close/Sync에러,os.Create.
2.2 데이터(Data)
- NUM numbers.md: 8진수 (
0644), 정수 오버플로우 (int32(,math.MaxInt), float==, NaN/Inf,math.FMA. - SLC slices.md: 길이/용량,
appendaliasing, 사전 할당 (make([]), nil/빈 ([]T{},s == nil),len검사,copy/slices.Clone,[low:high:max], 슬라이스-배열 변환. - COL collection-helpers.md:
min/max,slices삽입/삭제/정렬/검색,maps,cmp,clear. 이전 형태:sort.Slice,math.Min/math.Max,append(s[:i], s[i+1:]...), map 클리어delete루프. - MAP maps.md: 맵 크기 지정 (
make(map,map[K]V{}), 정렬된 키 (maps.Keys,sort.Strings), 맵 순회 중 쓰기. - MRT memory-retention.md: 캐시/장수명 맵 (뮤텍스 옆 맵, 삭제, 최대치 이후 크기), 유지된 부분 문자열/부분 슬라이스, 버려진 포인터 제로화,
strings.Clone/bytes.Clone,runtime.AddCleanup/runtime.SetFinalizer,unique.*,weak.*. - CMP comparison.md: 비교 가능 타입 (인터페이스/구조체에
==,[T comparable]),slices.Equal/maps.Equal,reflect.DeepEqual, 함수 값 (runtime.FuncForPC). - STX strings-text.md: 바이트/룬 (
len(s)를 문자 수로 사용,[]rune), UTF-8 검증 (utf8),string(int), 문자열 range,unicode테이블. - SPR strings-processing.md:
Trim*/Cut*,SplitSeq/FieldsSeq/Lines,strings.Split/strings.Index,strings.Builder, 문자열+=루프,bytes/bytes.Buffer,fmt.Append*/strconv.Append*,[]byte(fmt.Sprintf(.
2.3 오류(Errors)
- PAN panics.md:
panicvserror,recover,Must,panic(nil)/panicnil,debug.SetCrashOutput. - ERC errors-creating.md: 래핑 (
%w/%v,fmt.Errorf, 컨텍스트 없는return err/return nil, err),errors.New, 센티넬 (var Err) vs 오류 타입 (Error() string),errors.Join,ErrUnsupported. - ERH errors-handling.md:
errors.Is/errors.AsType,err ==,err.(type),errors.As, 메시지 비교, 타임아웃/취소 센티넬 (net.Error,os.ErrDeadlineExceeded,context.DeadlineExceeded), 결과 전err확인, 무시된 오류 (_ =,x, _ :=). - LOG logging.md:
log/slog설정 및 오류 로깅,log.Printf/log.Println, 동일한 오류 로깅 및 반환.
2.4 동시성(Concurrency)
- CND concurrency-design.md: 동시성 vs 병렬성, 생성 임계값 (요소당 고루틴), 워커 풀 크기,
runtime.NumCPU(),GOMAXPROCS. - SHR shared-state.md: 데이터 경합, happens-before, 경쟁 조건, 뮤텍스 vs 채널, 고루틴 쓰기,
sync.Mutex/RLock, 락 내 포매팅 (fmt.Sprintf), 공유append/맵. - SYN sync-primitives.md: 타입이 있는 아토믹 (
sync/atomic,atomic.Pointer,atomic.AddInt64/atomic.Value, 고루틴n++),sync.Map,sync.Once/sync.OnceValue,sync.Cond, 복사된sync값. - GOR goroutine-lifecycle.md: 고루틴 누수, 중지 계획/소유자, 조기 반환 후 차단된 발신자, 버퍼 없는 결과 채널,
go func(),sync.WaitGroup,wg.Add/wg.Go, errgroup (g.Go,SetLimit). - CHA channels.md: 알림 채널 및 크기 지정 (
make(chan,chan bool,chan struct{}),select우선순위, nil 채널,close. - CTX context.md:
context.Context전달,defer cancel()/context.WithTimeout, 블로킹 연산 주변ctx.Done(), 값 키 (context.WithValue,ctx.Value),main외부의context.Background(). - CXC context-cancellation.md: 취소 원인 (
ctx.Err(),<-ctx.Done(),context.Canceled/context.DeadlineExceeded/context.Cause,WithCancelCause),context.AfterFunc, 백그라운드 작업 (WithoutCancel, 고루틴r.Context()),signal.Notify/signal.NotifyContext.
2.5 표준 라이브러리(Standard library)
- TIM time.md:
time.Duration단위/숫자만,time.Time비교 (==), 루프 내 타이머 (time.After),time.NewTimer,time.Tick. - JSN json.md:
encoding/json,encoding/json/v2, JSON 태그 (omitzero,omitempty), 임베디드 마샬러, 숫자 디코딩 (json.Unmarshaltomap[string]any). - SQL database-sql.md:
database/sql,sql.Open,PingContext, 풀 크기, 쿼리 인자/준비된 문 (db.Query,.Exec,QueryRow,ExecContext,fmt.Sprintf를 통한 SQL),sql.Null[T],rows.Next/rows.Err. - IOF io-and-files.md:
io.Reader/io.Writer및fs.FS파라미터,filename string,os.Open,os.ReadFile,os.DirFS,os.Root, 사용자 입력과 함께filepath.Join. - HCL http-client-and-net.md: 클라이언트 타임아웃/공유/풀 (
http.Get,http.Post,http.DefaultClient,http.Client,http.Transport),net/netipvsnet.IP/net.ParseIP,net.JoinHostPortvsfmt.Sprintf("%s:%d". - HSV http-server.md: 핸들러 (
http.ResponseWriter,*http.Request,http.Handler,r.Body/r.Method),ServeMux패턴/HandleFunc,http.Error, 서버 타임아웃 (http.ListenAndServe,http.Server),MaxBytesHandler,ResponseController,CrossOriginProtection. - RND randomness-and-ids.md:
uuid,crypto/rand,math/rand,math/rand/v2,rand.Seed.
2.6 테스팅(Testing)
- TBA testing-basics.md: 테스트 카테고리/빌드 태그 (
func TestX,//go:build integration),-race,t.Parallel,-shuffle, 테이블 기반 테스트/t.Run, 헬퍼, 외부_test패키지. - TST testing-state.md:
t.Cleanup,TestMain,t.Contextvs 테스트context.Background(),t.Chdir/t.Setenv/t.TempDirvsos.Chdir/os.Setenv/os.MkdirTemp,testing/synctest, 테스트 시간/time.Sleep,cryptotest. - TTL testing-tools.md:
httptest,testing/iotest,fstest,slogtest, 퍼징 (func FuzzX). - BEN benchmarks.md:
func BenchmarkX,b.Loopvsb.N/b.ResetTimer, 대표 입력/재사용,benchstat. - COV coverage-and-test-output.md:
-coverpkg,-cover,go build -cover/GOCOVERDIR,t.Output/t.Attr/t.ArtifactDir, 테스트fmt.Println,go test -json.
2.7 성능(Performance)
레이아웃, 할당, 인라인 실천 방법은 벤치마크, 프로파일 또는 트레이스에서 식별된 핫 경로에만 적용합니다.
- PRO profiling.md: pprof (
net/http/pprof,/debug/pprof,runtime/pprof,pprof.Lookup), 힙 diff, 고루틴 덤프,goroutineleak/block/뮤텍스 프로파일 (SetBlockProfileRate,SetMutexProfileFraction), 레이블 (pprof.Do), 고루틴 수 (runtime/metrics). - TRC tracing.md: 실행 트레이싱 (
runtime/trace,trace.Start), 비행 기록기 (FlightRecorder), 레이턴시 스파이크/드문 느린 요청, 스케줄링/GC 일시 중지. - MLY memory-layout.md: 캐시 지역성/스트라이드 (핫
[]*T루프), 거짓 공유 (하나의 슬라이스 내 고루틴별 카운터), 명령어 수준 병렬성, 필드 정렬,structs.HostLayout. - ALO allocations.md: 이스케이프 분석 (
-gcflags, 지역 포인터 반환), 호출자 소유 버퍼, 컴파일러 제거 변환 (핫string(b)),allocs/op,sync.Pool. - BRT build-and-runtime-tuning.md: 인라인, PGO (
default.pgo),GOGC/GOMEMLIMIT/debug.SetGCPercent, 컨테이너 인식GOMAXPROCS(automaxprocs,runtime.GOMAXPROCS). - CGO cgo.md: cgo 호출 배치 (
import "C",C.),#cgo지시문 (noescape,nocallback).
2.8 프로젝트 및 도구(Project and tooling)
- PKG packages-and-docs.md: 프로젝트 레이아웃, 패키지 응집력/이름 (
util,common), 별칭 (type X = Y,//go:fix inline), doc 주석, 누락된 exported doc 주석,Deprecated:, 예제 (func ExampleX). - TOL tooling.md:
gofmt,go vet, 린터 (golangci-lint),tool지시문/tools.go,go fixmodernizer, 테스트 vet 검사 (-vet=), CI 스크립트,@latest. - MOD modules-and-builds.md:
go.mod위생/replace,godebug///go:debug, 워크스페이스 (go.work), 빌드 제약 조건 (//go:build,// +build).
3. 작업에 적용(Apply to the task)
- 코드 작성: 경로에 있는 모든 파일의 각 적용 가능한 실천 방법을 충족합니다.
- 코드 리뷰: 명령을 사용할 수 있는 경우, 먼저
go vet ./...,go test -race ./...,go fix -diff ./...를 실행하되, 코드가 수정되지 않은 상태로 유지되어야 한다면 복사본을 사용합니다. 경로에 있는 모든 파일의 모든 Signals 항목을 확인합니다. Exceptions에서 다루는 적중은 제외합니다. 나머지는ID | file:line | 무엇이 잘못되었는지 | 수정 방법형식으로 보고합니다. 중복되는 실천 방법의 경우 가장 구체적인 ID를 먼저 인용하고, 그 다음 다른 ID를 인용합니다. 어떤 실천 방법에서도 다루지 않는 문제는-를 사용합니다. 영향을 기준으로 정렬합니다: 잘못된 결과, 경합, 패닉, 누수, 교착 상태, 그리고 리소스/성능 문제, 그리고 구식 관용구/스타일 순입니다. - 디버깅: 증상을 Signals 및 Why와 일치시키고, 코드에서 메커니즘을 확인한 후 Practice를 적용합니다.
- 코드 현대화:
go fix ./...를 diff가 없을 때까지 실행하여 modernizer를 적용하고, diff를 검토합니다. Modernizer는 안전하다고 증명할 수 없는 코드 형태를 건너뛰므로, 경로에 있는 파일의 Signals에서 나머지 구식 관용구를 확인하고 수동으로 다시 작성합니다. 경로에 있는 파일의 Signals 항목이 일치하는 것이 없고go vet ./...및 테스트가 통과하면 완료됩니다.
성능 향상을 주장하기 전에 벤치마크나 프로파일로 측정합니다.