コンテンツにスキップ

23 Go Best Practices Every Developer Should Know (with Examples)

チェック

  • [ ] 本文を確認した
  • [ ] 概要を確認した
  • [ ] タグを確認した
  • [ ] inbox/ 直下へ移行した

概要

23 Go Best Practices Every Developer Should Know (with Examples) のWebクリップ。本文からGo、AWS、Observability、設計、キャリア評価などの学習材料として使えそうな内容を保存した。関連タグ: go, web-clip。

本文

Sign up

Sign in

Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

23 Go Best Practices Every Developer Should Know (with Examples)

--

12

Listen

Share

Go is beloved for its clean syntax and powerful tooling, but true mastery comes from writing idiomatic, readable, and maintainable code. Both the Go Code Review Comments and Google’s Go Style Best Practices collect essential guidance that programmers should internalize.

In this article, you’ll discover 23 best practices — each illustrated with bad vs. good examples and explanations that clarify the rationale behind the recommended style.

gofmt

// ❌ Badfunc main( ) { fmt.Println("Hello, world") }// ✅ Goodfunc main() { fmt.Println("Hello, world")}

2. Write Comments That Explain Why, Not What

// ❌ Bad// Increment i by 1i = i + 1// ✅ Good// Retry count is increased after each failed attempt.i++

Why? Comments should add insight — not restate the obvious. A good comment clarifies intent.

3. Declare Empty Slices Idiomatically

// ❌ Bads := []int{}// ✅ Goodvar s []int

[]T{}

4. Write Useful Documentation Comments

// ❌ Bad// add adds two numbersfunc add(a, b int) int { return a + b }// ✅ Good// Add returns the sum of a and b.func Add(a, b int) int { return a + b}

Why? Doc comments should be full sentences, start with the name, and explain from the caller’s perspective.

panic

// ❌ Badfunc ReadConfig(path string) string { data, err := os.ReadFile(path) if err != nil { panic("failed to read config: " + err.Error()) } return string(data)}// ✅ Goodfunc ReadConfig(path string) (string, error) { data, err := os.ReadFile(path) if err != nil { return "", fmt.Errorf("read config: %w", err) } return string(data), nil}

6. Keep Error Strings Clean

// ❌ Badreturn fmt.Errorf("File Not Found.")// ✅ Goodreturn fmt.Errorf("file not found")

Why? Error messages should start lowercase, avoid punctuation, and compose cleanly.

7. Handle Errors with Early Returns

// ❌ Badif err != nil { if something { return err }} else { doWork()}// ✅ Goodif err != nil { return err}doWork()

Why? Early returns reduce nesting and clarify the main logic path.

8. Avoid Dot-Imports

// ❌ Badimport . "fmt"// ✅ Goodimport "fmt"

Why? Dot-imports obscure where symbols come from; explicit imports improve clarity.

9. Capitalize Initialisms Properly

// ❌ Badtype HttpServer struct {}// ✅ Goodtype HTTPServer struct{}

Why? Initialisms should stay uppercase (HTTP, ID, JSON) for consistency with the standard library.

10. Use MixedCaps, Not Underscores

// ❌ Badvar user_name string// ✅ Goodvar userName string

mixedCaps

MixedCaps

11. Avoid Naked Returns in Larger Functions

// ❌ Badfunc sum(a, b int) (result int) { result = a + b return}// ✅ Goodfunc sum(a, b int) int { return a + b}

Why? Naked returns may obscure return values in complex functions.

12. Keep Package Names Simple

// ❌ Badpackage my_utils// ✅ Goodpackage utils

Why? Package names should be lowercase, concise, and without underscores — serving as readable APIs.

13. Choose Clear Receiver Names

// ❌ Badfunc (this *Server) Start() {}// ✅ Goodfunc (s *Server) Start() {}

14. Keep Interfaces Minimal

// ❌ Badtype Database interface { Connect() Query() Close()}// ✅ Goodtype Querier interface { Query(query string) (Result, error)}

Why? Small interfaces focused on use make mocking and reasoning easier.

15. Avoid Repetition in Function Names

// ❌ Badpackage yamlconfigfunc ParseYAMLConfig(input string) (*Config, error)// ✅ Goodpackage yamlconfigfunc Parse(input string) (*Config, error)

Why? Avoid redundant words — the call site already shows context.

16. Method Names: Skip Repetitive Receiver Words

// ❌ Badfunc (c *Config) WriteConfigTo(w io.Writer) (int64, error)// ✅ Goodfunc (c *Config) WriteTo(w io.Writer) (int64, error)

Why? Don’t repeat receiver type in method names — brevity improves clarity.

17. Don’t Repeat Parameter Names in Function Signatures

// ❌ Badfunc OverrideFirstWithSecond(dest, source *Config) error// ✅ Goodfunc Override(dest, source *Config) error

Why? Avoid redundancy — the context is clear from parameter roles.

18. Do Not Duplicate Return Value Types in Names

// ❌ Badfunc TransformToJSON(input *Config) *jsonconfig.Config// ✅ Goodfunc Transform(input *Config) *jsonconfig.Config

19. Name Functions Properly: Nouns vs. Verbs

// ❌ Badfunc (c *Config) GetJobName(key string) (value string, ok bool)// ✅ Goodfunc (c *Config) JobName(key string) (value string, ok bool)

Why? Functions returning values should use noun-like names; operations should use verbs.

20. Method Names Should Reflect Action vs. Retrieval

// Good examples showing verb-like names when doing something:func (c *Config) ApplyChanges() errorfunc ProcessData(data []byte) error

Why? Clarity through consistent naming — actions use verbs; data access uses nouns.

21. Pick Descriptive Variable Names

// ❌ Badx := getConfiguration()// ✅ Goodcfg := getConfiguration()

Why? Short but descriptive names make code easier to follow.

context.Context

// ❌ Badfunc fetchData(id string, ctx context.Context) {}// ✅ Goodfunc fetchData(ctx context.Context, id string) {}

23. Write Tests the Go Way

// ❌ Badif got != want { t.Errorf("expected %v but got %v", want, got)}// ✅ Goodif got != want { t.Errorf("got %v, want %v", got, want)}

got, want

Get Gopher’s stories in your inbox

Join Medium for free to get updates from this writer.

Remember me for faster sign in

Writing idiomatic Go hinges on clarity, simplicity, and consistency. Combining the wisdom of the Code Review Comments wiki with Google’s Best Practices gives you a richer, more polished grasp of what makes Go code shine.

Use this as your guide through code reviews, pair programming, and everyday development.

Enjoyed this post?

I write everything here for free — no paywall, no ads. If it helped you or saved you time, consider buying me a coffee☕. It really helps me keep writing and sharing more content like this. Thanks for reading! 🙌

Published in Stackademic

Written by Gopher

Architecting Scalable Software | Free Blogs for Curious Minds

Help

Status

About

Careers

Press

Blog

Privacy

Rules

Terms

Text to speech

要点

  • Goの実装・設計・標準的な書き方を面接や実務の深掘り材料にする。
  • 元URL: https://blog.stackademic.com/23-go-best-practices-every-developer-should-know-with-examples-405772530d8f?gi=16631c6949c4

タグ

go #web-clip