557b2c2441 | ||
---|---|---|
.gitignore | ||
LICENSE | ||
README.md |
README.md
uber-go-style-guide-kr
Translated in Korean
Currently WIP, but translation will done by 20th of Oct, 2019
Uber의 Go언어 스타일 가이드 (Uber's Go Style Guide)
- uber-go-style-guide-kr
- Uber의 Go언어 스타일 가이드 (Uber's Go Style Guide)
- 소개 (Introduction)
- 가이드라인 (Guidelines)
- 인터페이스에 대한 포인터 (Pointers to Interfaces)
- 수신자(Receivers)와 인터페이스(Interfaces)
- 제로 값 뮤텍스(Zero-value Mutexes)는 유효하다
- 슬라이스 복사(Copy Slices)와 바운더리 에서의 맵(Maps at Boundaries)
- Defer to Clean Up
- Channel Size is One or None
- Start Enums at One
- Error Types
- Error Wrapping
- Handle Type Assertion Failures
- Don't Panic
- Use go.uber.org/atomic
- Performance
- Style
- Group Similar Declarations
- Import Group Ordering
- Package Names
- Function Names
- Import Aliasing
- Function Grouping and Ordering
- Reduce Nesting
- Unnecessary Else
- Top-level Variable Declarations
- Prefix Unexported Globals with _
- Embedding in Structs
- Use Field Names to initialize Structs
- Local Variable Declarations
- nil is a valid slice
- Reduce Scope of Variables
- Avoid Naked Parameters
- Use Raw String Literals to Avoid Escaping
- Initializing Struct References
- Format Strings outside Printf
- Naming Printf-style Functions
- Patterns
소개 (Introduction)
스타일은 코드를 통제하는(govern) 관습이다. 이러한 관습(convention)은 소스파일 포맷팅 (e.g. gofmt)보다 더 많은 영역을 다루기(cover) 때문에, "스타일" 이라는 단어 자체가 약간 부적절 할 수 있다.
본 가이드의 목표는 Uber에서 Go 코드를 작성할 때 해야 할 것과 하지 말아야 할 것 (Dos and Don'ts)에 대하여 자세하게 설명하여 이러한 복잡성을 관리하는 것이다. 이런 규칙들은 엔지니어들이 Go 언어의 특성을(feature) 생산적으로개계속 사용할 수 있도록 코드 베이스를 관리가능하게 유지하기위해 존재한다.
이 가이드는 원래 Prashant Varanasi와 Simon Newton이 동료들에게 Go를 사용하면서 개발속도 향상을 도모하기 위해 소개되었다. 또한, 수 년에 거쳐서 다른 사람들로부터의 피드백을 통해서 개정되 오고 있다.
이 문서는 Uber에서의 엔지니어들이 지향하는 Go언어 코드의 관용적 규칙을 설명한다. 상당 수의 규칙들은 Go언어에 대한 일반적인 가이드라인이며, 다른 부분에 대해서는 외부 레퍼런스에 의해 확장된다 (아래 참고)
모든 코드는 golint
와 go vet
를 실행할 때 에러가 없어야 한다. 또한 우리는 여러분들의 에디터를 아래와 같이 설정하기를 권고한다:
- Run
goimports
on save - Run
golint
andgo vet
to check for errors
아래의 링크를 통해서 Go 툴을 지원하는 에디터에 대한 정보를 얻을 수 있다: https://github.com/golang/go/wiki/IDEsAndTextEditorPlugins
가이드라인 (Guidelines)
인터페이스에 대한 포인터 (Pointers to Interfaces)
일반적으로 인터페이스에 대한 포인터는 거의 필요하지 않을 것이다. 여러분들은 인터페이스를 값(value)으로서 전달(passing)해야 할 것이며, 인터페이스에 대한 기본 데이터(underlying data)는 여전히 포인터가 될 수 있다.
한 인터페이스는 두 가지 필드이다:
- 타입-특정 정보(type-specific information)에 대한 포인터. 여러분들을 이것을 "타입"으로 간주할 수 있다.
- 데이터 포인터. 저장된 데이터가 포인터일 경우, 이것은 직접적으로 저장될 수 있다. 만약, 저장된 데이터가 값(value)인 경우, 값에 대한 포인터가 저장된다.
만약 여러분들이 기본 데이터(underlying data) 수정하기 위한 인터페이스 메서드 (interface methods)를 원한다면, 여러분들은 반드시 포인터를 사용해야 한다.
수신자(Receivers)와 인터페이스(Interfaces)
값 수신자 (value receivers)와 메서드(Methods)는 포인터 혹은 값에 의해서 호출 될 수 있다.
예를 들면,
type S struct {
data string
}
func (s S) Read() string {
return s.data
}
func (s *S) Write(str string) {
s.data = str
}
sVals := map[int]S{1: {"A"}}
// 오직 값만 사용하여 Read를 호출 할 수 있다.
sVals[1].Read()
// 아래 코드는 컴파일 되지 않을 것:
// sVals[1].Write("test")
sPtrs := map[int]*S{1: {"A"}}
// 포인터를 사용하여 Read와 Write 모두 호출 할 수 있다.
sPtrs[1].Read()
sPtrs[1].Write("test")
마찬가지로, 메서드가 값 수신자(value receiver)를 가지고 있다고 하더라도 포인터가 인터페이스를 충족시킬 수 있다.
type F interface {
f()
}
type S1 struct{}
func (s S1) f() {}
type S2 struct{}
func (s *S2) f() {}
s1Val := S1{}
s1Ptr := &S1{}
s2Val := S2{}
s2Ptr := &S2{}
var i F
i = s1Val
i = s1Ptr
i = s2Ptr
// s2Val이 값이고 f에 대한 수신자가 없기 때문에, 아래의 코드는 컴파일 되지 않는다.
// i = s2Val
Effective Go에 Pointers vs. Values에 대한 좋은 글이 있으니 참고하기 바란다.
제로 값 뮤텍스(Zero-value Mutexes)는 유효하다
sync.Mutex
와 sync.RWMutex
의 제로 값은 유효하므로, 거의 대부분의 경우 뮤텍스에 대한 포인터는 필요로 하지 않는다.
Bad | Good |
---|---|
|
|
포인터로 구조체를 사용할 경우, 뮤텍스는 포인터가 아닌 필드(non-pointer field)가 될 수 있다.
구조체의 필드를 보호하기 위해 뮤텍스를 사용한 수출되지 않는 구조체(unexported structs)는 뮤텍스를 포함(embed) 할 수 있다.
|
|
뮤텍스 인터페이스를 구현해야 하는 전용 타입(private type) 혹은 타입에 포함됨. | 수출되는 타입(exported type)에 대해서는 전용 필드 (private field)를 사용함. |
슬라이스 복사(Copy Slices)와 바운더리 에서의 맵(Maps at Boundaries)
슬라이스(Slices)와 맵(maps)은 기본 데이터(underlying data)에 대한 포인터를 포함하고 있으므로 이들을 복사 해야 할 때의 시나리오에 대해서 주의할 필요가 있다.
Slices와 Maps의 수신(receiving)
참조/레퍼런스(reference)를 저장할 경우, 사용자는 인수(argument)로 받는 맵 혹은 슬라이스를 수정할 수 있음을 명심하라.
Bad | Good |
---|---|
|
|
Returning Slices and Maps
Similarly, be wary of user modifications to maps or slices exposing internal state.
Bad | Good |
---|---|
|
|
Defer to Clean Up
Use defer to clean up resources such as files and locks.
Bad | Good |
---|---|
|
|
Defer has an extremely small overhead and should be avoided only if you can
prove that your function execution time is in the order of nanoseconds. The
readability win of using defers is worth the miniscule cost of using them. This
is especially true for larger methods that have more than simple memory
accesses, where the other computations are more significant than the defer
.
Channel Size is One or None
Channels should usually have a size of one or be unbuffered. By default, channels are unbuffered and have a size of zero. Any other size must be subject to a high level of scrutiny. Consider how the size is determined, what prevents the channel from filling up under load and blocking writers, and what happens when this occurs.
Bad | Good |
---|---|
|
|
Start Enums at One
The standard way of introducing enumerations in Go is to declare a custom type
and a const
group with iota
. Since variables have a 0 default value, you
should usually start your enums on a non-zero value.
Bad | Good |
---|---|
|
|
There are cases where using the zero value makes sense, for example when the zero value case is the desirable default behavior.
type LogOutput int
const (
LogToStdout LogOutput = iota
LogToFile
LogToRemote
)
// LogToStdout=0, LogToFile=1, LogToRemote=2
Error Types
There are various options for declaring errors:
errors.New
for errors with simple static stringsfmt.Errorf
for formatted error strings- Custom types that implement an
Error()
method - Wrapped errors using
"pkg/errors".Wrap
When returning errors, consider the following to determine the best choice:
-
Is this a simple error that needs no extra information? If so,
errors.New
should suffice. -
Do the clients need to detect and handle this error? If so, you should use a custom type, and implement the
Error()
method. -
Are you propagating an error returned by a downstream function? If so, check the section on error wrapping.
-
Otherwise,
fmt.Errorf
is okay.
If the client needs to detect the error, and you have created a simple error
using errors.New
, use a var for the error.
Bad | Good |
---|---|
|
|
If you have an error that clients may need to detect, and you would like to add more information to it (e.g., it is not a static string), then you should use a custom type.
Bad | Good |
---|---|
|
|
Be careful with exporting custom error types directly since they become part of the public API of the package. It is preferable to expose matcher functions to check the error instead.
// package foo
type errNotFound struct {
file string
}
func (e errNotFound) Error() string {
return fmt.Sprintf("file %q not found", e.file)
}
func IsNotFoundError(err error) bool {
_, ok := err.(errNotFound)
return ok
}
func Open(file string) error {
return errNotFound{file: file}
}
// package bar
if err := foo.Open("foo"); err != nil {
if foo.IsNotFoundError(err) {
// handle
} else {
panic("unknown error")
}
}
Error Wrapping
There are three main options for propagating errors if a call fails:
- Return the original error if there is no additional context to add and you want to maintain the original error type.
- Add context using
"pkg/errors".Wrap
so that the error message provides more context and"pkg/errors".Cause
can be used to extract the original error. - Use
fmt.Errorf
if the callers do not need to detect or handle that specific error case.
It is recommended to add context where possible so that instead of a vague error such as "connection refused", you get more useful errors such as "call service foo: connection refused".
When adding context to returned errors, keep the context succinct by avoiding phrases like "failed to", which state the obvious and pile up as the error percolates up through the stack:
Bad | Good |
---|---|
|
|
|
|
However once the error is sent to another system, it should be clear the
message is an error (e.g. an err
tag or "Failed" prefix in logs).
See also Don't just check errors, handle them gracefully.
Handle Type Assertion Failures
The single return value form of a type assertion will panic on an incorrect type. Therefore, always use the "comma ok" idiom.
Bad | Good |
---|---|
|
|
Don't Panic
Code running in production must avoid panics. Panics are a major source of cascading failures. If an error occurs, the function must return an error and allow the caller to decide how to handle it.
Bad | Good |
---|---|
|
|
Panic/recover is not an error handling strategy. A program must panic only when something irrecoverable happens such as a nil dereference. An exception to this is program initialization: bad things at program startup that should abort the program may cause panic.
var _statusTemplate = template.Must(template.New("name").Parse("_statusHTML"))
Even in tests, prefer t.Fatal
or t.FailNow
over panics to ensure that the
test is marked as failed.
Bad | Good |
---|---|
|
|
Use go.uber.org/atomic
Atomic operations with the sync/atomic package operate on the raw types
(int32
, int64
, etc.) so it is easy to forget to use the atomic operation to
read or modify the variables.
go.uber.org/atomic adds type safety to these operations by hiding the
underlying type. Additionally, it includes a convenient atomic.Bool
type.
Bad | Good |
---|---|
|
|
Performance
Performance-specific guidelines apply only to the hot path.
Prefer strconv over fmt
When converting primitives to/from strings, strconv
is faster than
fmt
.
Bad | Good |
---|---|
|
|
|
|
Avoid string-to-byte conversion
Do not create byte slices from a fixed string repeatedly. Instead, perform the conversion once and capture the result.
Bad | Good |
---|---|
|
|
|
|
Style
Group Similar Declarations
Go supports grouping similar declarations.
Bad | Good |
---|---|
|
|
This also applies to constants, variables, and type declarations.
Bad | Good |
---|---|
|
|
Only group related declarations. Do not group declarations that are unrelated.
Bad | Good |
---|---|
|
|
Groups are not limited in where they can be used. For example, you can use them inside of functions.
Bad | Good |
---|---|
|
|
Import Group Ordering
There should be two import groups:
- Standard library
- Everything else
This is the grouping applied by goimports by default.
Bad | Good |
---|---|
|
|
Package Names
When naming packages, choose a name that is:
- All lower-case. No capitals or underscores.
- Does not need to be renamed using named imports at most call sites.
- Short and succinct. Remember that the name is identified in full at every call site.
- Not plural. For example,
net/url
, notnet/urls
. - Not "common", "util", "shared", or "lib". These are bad, uninformative names.
See also Package Names and Style guideline for Go packages.
Function Names
We follow the Go community's convention of using MixedCaps for function
names. An exception is made for test functions, which may contain underscores
for the purpose of grouping related test cases, e.g.,
TestMyFunction_WhatIsBeingTested
.
Import Aliasing
Import aliasing must be used if the package name does not match the last element of the import path.
import (
"net/http"
client "example.com/client-go"
trace "example.com/trace/v2"
)
In all other scenarios, import aliases should be avoided unless there is a direct conflict between imports.
Bad | Good |
---|---|
|
|
Function Grouping and Ordering
- Functions should be sorted in rough call order.
- Functions in a file should be grouped by receiver.
Therefore, exported functions should appear first in a file, after
struct
, const
, var
definitions.
A newXYZ()
/NewXYZ()
may appear after the type is defined, but before the
rest of the methods on the receiver.
Since functions are grouped by receiver, plain utility functions should appear towards the end of the file.
Bad | Good |
---|---|
|
|
Reduce Nesting
Code should reduce nesting where possible by handling error cases/special conditions first and returning early or continuing the loop. Reduce the amount of code that is nested multiple levels.
Bad | Good |
---|---|
|
|
Unnecessary Else
If a variable is set in both branches of an if, it can be replaced with a single if.
Bad | Good |
---|---|
|
|
Top-level Variable Declarations
At the top level, use the standard var
keyword. Do not specify the type,
unless it is not the same type as the expression.
Bad | Good |
---|---|
|
|
Specify the type if the type of the expression does not match the desired type exactly.
type myError struct{}
func (myError) Error() string { return "error" }
func F() myError { return myError{} }
var _e error = F()
// F returns an object of type myError but we want error.
Prefix Unexported Globals with _
Prefix unexported top-level var
s and const
s with _
to make it clear when
they are used that they are global symbols.
Exception: Unexported error values, which should be prefixed with err
.
Rationale: Top-level variables and constants have a package scope. Using a generic name makes it easy to accidentally use the wrong value in a different file.
Bad | Good |
---|---|
|
|
Embedding in Structs
Embedded types (such as mutexes) should be at the top of the field list of a struct, and there must be an empty line separating embedded fields from regular fields.
Bad | Good |
---|---|
|
|
Use Field Names to initialize Structs
You should almost always specify field names when initializing structs. This is
now enforced by go vet
.
Bad | Good |
---|---|
|
|
Exception: Field names may be omitted in test tables when there are 3 or fewer fields.
tests := []struct{
op Operation
want string
}{
{Add, "add"},
{Subtract, "subtract"},
}
Local Variable Declarations
Short variable declarations (:=
) should be used if a variable is being set to
some value explicitly.
Bad | Good |
---|---|
|
|
However, there are cases where the default value is clearer when the var
keyword is use. Declaring Empty Slices, for example.
Bad | Good |
---|---|
|
|
nil is a valid slice
nil
is a valid slice of length 0. This means that,
-
You should not return a slice of length zero explicitly. Return
nil
instead.Bad Good if x == "" { return []int{} }
if x == "" { return nil }
-
To check if a slice is empty, always use
len(s) == 0
. Do not check fornil
.Bad Good func isEmpty(s []string) bool { return s == nil }
func isEmpty(s []string) bool { return len(s) == 0 }
-
The zero value (a slice declared with
var
) is usable immediately withoutmake()
.Bad Good nums := []int{} // or, nums := make([]int) if add1 { nums = append(nums, 1) } if add2 { nums = append(nums, 2) }
var nums []int if add1 { nums = append(nums, 1) } if add2 { nums = append(nums, 2) }
Reduce Scope of Variables
Where possible, reduce scope of variables. Do not reduce the scope if it conflicts with Reduce Nesting.
Bad | Good |
---|---|
|
|
If you need a result of a function call outside of the if, then you should not try to reduce the scope.
Bad | Good |
---|---|
|
|
Avoid Naked Parameters
Naked parameters in function calls can hurt readability. Add C-style comments
(/* ... */
) for parameter names when their meaning is not obvious.
Bad | Good |
---|---|
|
|
Better yet, replace naked bool
types with custom types for more readable and
type-safe code. This allows more than just two states (true/false) for that
parameter in the future.
type Region int
const (
UnknownRegion Region = iota
Local
)
type Status int
const (
StatusReady = iota + 1
StatusDone
// Maybe we will have a StatusInProgress in the future.
)
func printInfo(name string, region Region, status Status)
Use Raw String Literals to Avoid Escaping
Go supports raw string literals, which can span multiple lines and include quotes. Use these to avoid hand-escaped strings which are much harder to read.
Bad | Good |
---|---|
|
|
Initializing Struct References
Use &T{}
instead of new(T)
when initializing struct references so that it
is consistent with the struct initialization.
Bad | Good |
---|---|
|
|
Format Strings outside Printf
If you declare format strings for Printf
-style functions outside a string
literal, make them const
values.
This helps go vet
perform static analysis of the format string.
Bad | Good |
---|---|
|
|
Naming Printf-style Functions
When you declare a Printf
-style function, make sure that go vet
can detect
it and check the format string.
This means that you should use pre-defined Printf
-style function
names if possible. go vet
will check these by default. See Printf family
for more information.
If using the pre-defined names is not an option, end the name you choose with
f: Wrapf
, not Wrap
. go vet
can be asked to check specific Printf
-style
names but they must end with f.
$ go vet -printfuncs=wrapf,statusf
See also go vet: Printf family check.
Patterns
Test Tables
Use table-driven tests with subtests to avoid duplicating code when the core test logic is repetitive.
Bad | Good |
---|---|
|
|
Test tables make it easier to add context to error messages, reduce duplicate logic, and add new test cases.
We follow the convention that the slice of structs is referred to as tests
and each test case tt
. Further, we encourage explicating the input and output
values for each test case with give
and want
prefixes.
tests := []struct{
give string
wantHost string
wantPort string
}{
// ...
}
for _, tt := range tests {
// ...
}
Functional Options
Functional options is a pattern in which you declare an opaque Option
type
that records information in some internal struct. You accept a variadic number
of these options and act upon the full information recorded by the options on
the internal struct.
Use this pattern for optional arguments in constructors and other public APIs that you foresee needing to expand, especially if you already have three or more arguments on those functions.
Bad | Good |
---|---|
|
|
See also,