- Always use enum for status field
- Push Ifs Up: Move if condition from inside function to caller when the if condition is returning early
- Push Fors Down: Prefer passing list of objects to function instead of function inside loop of objects, to allow batch operation
- Provide capacity when
makemaps, slices - Use field name to init struct
- Do not use unsigned type
- Do not edit/update map argument inside function, to avoid race condition
- Review all string comparison
==,!=to evaluate if need to usestrings.EqualFoldinstead
Since go 1.26:
- Use
a := new(1) - Use
errors.AsTypeinstead oferrors.As
Since go 1.24:
- Use
os.Rootinstead ofos.Open - Use
omitzeroinstead ofomitempty
Since go 1.22:
- Use
cmp.Oras fallback mechanism
Since go 1.21:
- Use
slices.SortFuncinstead ofsort.Slice. - Use
ctx.WithoutCancelto disconnect context from parent. - Use
clear(m)to clear map entirely.
Since go 1.20:
- Use
errors.Joinfor multiple errors.
Since go 1.18:
- Use
anyinstead ofinterface{}.
Use gopls/modernize to modernize code.
modernize -fix -test ./...- Don't use
cwhen passing context, usec.Request.Context()instead - Don't use
c.Request.URL.Path, usec.FullPath()instead
- Use
MarshalLogObjectwhen need to hide PII or long fields - Prefer
DPanictoPanic - Use
Fatalwhen init service - If doubt, use
zap.Any
- Prefer
PipelinedtoPipeline
- Use
spf13/castto cast from int to string, string to int - Use
bytedance/sonic, keepjson.Marshalbut prefersonic.Unmarshal,sonic.UnmarshalStringtojson.Unmarshal - Use
DATA-DOG/go-sqlmockfor mock sql testing- Use
sqlmock.QueryMatcherEqualinstead ofsqlmock.QueryMatcherRegexp
- Use
- Use
alicebob/miniredisfor mock redis testing
- Don't use database auto increment
- Use UUIDv7 (sortable) instead of UUIDv4 (completely random)
Don't use database type timestamp (MySQL timestamp, ...), use int64 then pass the timestamp (prefer UnixMilli) to avoid date, time, location complex conversion.
- Use
JSON_CONTAINS_PATH(col, 'one', '$.key')to check json field exist or not - Use
col->'$.key'to get value
Be careful if edit/cut string which has emoji before saving to database.
If compare not equal with NULL field, remember to check NULL.
-- field_something can be NULL
-- Bad
SELECT *
FROM table
WHERE field_something != 1
-- Good
SELECT *
FROM table
WHERE (field_something IS NULL OR field_something != 1)