notque/vexjoy-agent / skills/programming/programming
programming
FlaggedLanguage rules, workflows, and tooling: Go, Python, Rust, Kotlin, Swift, PHP, TypeScript type checks and debugging, OpenStack Python, MCP local-docs servers, Node.js backend APIs.
references/go/google-style-guide/decisions/part-03.md
View on GitHub
* Example command-line invocations and API usage can be useful documentation.
For Godoc formatting, indent the comment lines containing code.
* If there is no obvious primary file or if the package comment is
extraordinarily long, it is acceptable to put the doc comment in a file
named `doc.go` with only the comment and the package clause.
* Multiline comments can be used instead of multiple single-line comments.
This is primarily useful if the documentation contains sections which may be
useful to copy and paste from the source file, as with sample command-lines
(for binaries) and template examples.
```go
// Good:
/*
The seed_generator command is a utility that generates a Finch seed file
from a set of JSON study configs.
seed_generator *.json | base64 > finch-seed.base64
*/
package template
```
* Comments intended for maintainers and that apply to the whole file are
typically placed after import declarations. These are not surfaced in Godoc
and are not subject to the rules above on package comments.
<a id="imports"></a>
## Imports
<a id="TOC-Imports"></a>
<a id="import-renaming"></a>
### Import renaming
Package imports shouldn't normally be renamed, but there are cases where they
must be renamed or where a rename improves readability.
Local names for imported packages must follow
[the guidance around package naming](#package-names), including the prohibition
on the use of underscores and capital letters. Try to be
[consistent](guide#consistency) by always using the same local name for the same
imported package.
An imported package *must* be renamed to avoid a name collision with other
imports. (A corollary of this is that [good package names](#package-names)
should not require renaming.) In the event of a name collision, prefer to rename
the most local or project-specific import.
Generated protocol buffer packages *must* be renamed to remove underscores from
their names, and their local names must have a `pb` suffix. See
[proto and stub best practices](best-practices#import-protos) for more
information.
```go
// Good:
import (
foosvcpb "path/to/package/foo_service_go_proto"
)
```
Lastly, an imported, non-autogenerated package *can* be renamed if it has an
uninformative name (e.g. `util` or `v1`) Do this sparingly: do not rename the
package if the code surrounding the use of the package conveys enough context.
When possible, prefer refactoring the package itself with a more suitable name.
```go
// Good:
import (
core "github.com/kubernetes/api/core/v1"
meta "github.com/kubernetes/apimachinery/pkg/apis/meta/v1beta1"
)
```
If you need to import a package whose name collides with a common local variable
name that you want to use (e.g. `url`, `ssh`) and you wish to rename the
package, the preferred way to do so is with the `pkg` suffix (e.g. `urlpkg`).
Note that it is possible to shadow a package with a local variable; this rename
is only necessary if the package still needs to be used when such a variable is
in scope.
<a id="import-grouping"></a>
### Import grouping
Imports should be organized into the following groups, in order:
1. Standard library packages
1. Other (project and vendored) packages
1. Protocol Buffer imports (e.g., `fpb "path/to/foo_go_proto"`)
1. Import for [side-effects](https://go.dev/doc/effective_go#blank_import)
(e.g., `_ "path/to/package"`)
```go
// Good:
package main
import (
"fmt"
"hash/adler32"
"os"
"github.com/dsnet/compress/flate"
"golang.org/x/text/encoding"
"google.golang.org/protobuf/proto"
foopb "myproj/foo/proto/proto"
_ "myproj/rpc/protocols/dial"
_ "myproj/security/auth/authhooks"
)
```
<a id="import-blank"></a>
### Import "blank" (`import _`)
<a id="TOC-ImportBlank"></a>
Packages that are imported only for their side effects (using the syntax `import
_ "package"`) may only be imported in a main package, or in tests that require
them.
Some examples of such packages include:
* [time/tzdata](https://pkg.go.dev/time/tzdata)
* [image/jpeg](https://pkg.go.dev/image/jpeg) in image processing code
Avoid blank imports in library packages, even if the library indirectly depends
on them. Constraining side-effect imports to the main package helps control
dependencies, and makes it possible to write tests that rely on a different
import without conflict or wasted build costs.
The following are the only exceptions to this rule:
* You may use a blank import to bypass the check for disallowed imports in the
[nogo static checker].
* You may use a blank import of the [embed](https://pkg.go.dev/embed) package
in a source file which uses the `//go:embed` compiler directive.
**Tip:** If you create a library package that indirectly depends on a
side-effect import in production, document the intended usage.
[nogo static checker]: https://github.com/bazelbuild/rules_go/blob/master/go/nogo.rst
<a id="import-dot"></a>
### Import "dot" (`import .`)
<a id="TOC-ImportDot"></a>
The `import .` form is a language feature that allows bringing identifiers
exported from another package to the current package without qualification. See
the [language spec](https://go.dev/ref/spec#Import_declarations) for more.
Do **not** use this feature in the Google codebase; it makes it harder to tell
where the functionality is coming from.
```go
// Bad:
package foo_test
import (
"bar/testutil" // also imports "foo"
. "foo"
)
var myThing = Bar() // Bar defined in package foo; no qualification needed.
```
```go
// Good:
package foo_test
import (
"bar/testutil" // also imports "foo"
"foo"
)
var myThing = foo.Bar()
```
<a id="errors"></a>
## Errors
<a id="returning-errors"></a>
### Returning errors
<a id="TOC-ReturningErrors"></a>
Use `error` to signal that a function can fail. By convention, `error` is the
last result parameter.
```go
// Good:
func Good() error { /* ... */ }
```
Returning a `nil` error is the idiomatic way to signal a successful operation
that could otherwise fail. If a function returns an error, callers must treat
all non-error return values as unspecified unless explicitly documented
otherwise. Commonly, the non-error return values are their zero values, but this
cannot be assumed.
```go
// Good:
func GoodLookup() (*Result, error) {
// ...
if err != nil {
return nil, err
}
return res, nil
}
```
Exported functions that return errors should return them using the `error` type.
Concrete error types are susceptible to subtle bugs: a concrete `nil` pointer
can get wrapped into an interface and thus become a non-nil value (see the
[Go FAQ entry on the topic][nil error]).
```go
// Bad:
func Bad() *os.PathError { /*...*/ }
```
**Tip:** A function that takes a [`context.Context`] argument should usually
return an `error` so that the caller can determine if the context was cancelled
while the function was running.
[nil error]: https://golang.org/doc/faq#nil_error
<a id="error-strings"></a>
### Error strings
<a id="TOC-ErrorStrings"></a>
Error strings should not be capitalized (unless beginning with an exported name,
a proper noun or an acronym) and should not end with punctuation. This is
because error strings usually appear within other context before being printed
to the user.
```go
// Bad:
err := fmt.Errorf("Something bad happened.")
```
```go
// Good:
err := fmt.Errorf("something bad happened")
```
On the other hand, the style for the full displayed message (logging, test
failure, API response, or other UI) depends, but should typically be
capitalized.
```go
// Good:
log.Infof("Operation aborted: %v", err)
log.Errorf("Operation aborted: %v", err)
t.Errorf("Op(%q) failed unexpectedly; err=%v", args, err)
```
<a id="handle-errors"></a>
### Handle errors
<a id="TOC-HandleErrors"></a>
Code that encounters an error should make a deliberate choice about how to
handle it. It is not usually appropriate to discard errors using `_` variables.
If a function returns an error, do one of the following:
* Handle and address the error immediately.
* Return the error to the caller.
* In exceptional situations, call [`log.Fatal`] or (if absolutely necessary)
`panic`.
**Note:** `log.Fatalf` is not the standard library log. See [#logging].
In the rare circumstance where it is appropriate to ignore or discard an error
(for example a call to [`(*bytes.Buffer).Write`] that is documented to never
fail), an accompanying comment should explain why this is safe.
```go
// Good:
var b *bytes.Buffer
n, _ := b.Write(p) // never returns a non-nil error
```
For more discussion and examples of error handling, see
[Effective Go](http://golang.org/doc/effective_go.html#errors) and
[best practices](best-practices.md#error-handling).
[`(*bytes.Buffer).Write`]: https://pkg.go.dev/bytes#Buffer.Write
<a id="in-band-errors"></a>
### In-band errors
<a id="TOC-In-Band-Errors"></a>
In C and similar languages, it is common for functions to return values like -1,
null, or the empty string to signal errors or missing results. This is known as
in-band error handling.
```go
// Bad:
// Lookup returns the value for key or -1 if there is no mapping for key.
func Lookup(key string) int
```
Failing to check for an in-band error value can lead to bugs and can attribute
errors to the wrong function.
```go
// Bad:
// The following line returns an error that Parse failed for the input value,
// whereas the failure was that there is no mapping for missingKey.
return Parse(Lookup(missingKey))
```
Go's support for multiple return values provides a better solution (see the
[Effective Go section on multiple returns]). Instead of requiring clients to
check for an in-band error value, a function should return an additional value
to indicate whether its other return values are valid. This return value may be
an error or a boolean when no explanation is needed, and should be the final
return value.
```go
// Good:
// Lookup returns the value for key or ok=false if there is no mapping for key.
func Lookup(key string) (value string, ok bool)
```
This API prevents the caller from incorrectly writing `Parse(Lookup(key))` which
causes a compile-time error, since `Lookup(key)` has 2 outputs.
Returning errors in this way encourages more robust and explicit error handling:
```go
// Good:
value, ok := Lookup(key)
if !ok {
return fmt.Errorf("no value for %q", key)
}
return Parse(value)
```
Some standard library functions, like those in package `strings`, return in-band
error values. This greatly simplifies string-manipulation code at the cost of
requiring more diligence from the programmer. In general, Go code in the Google
codebase should return additional values for errors.
[Effective Go section on multiple returns]: http://golang.org/doc/effective_go.html#multiple-returns
<a id="indent-error-flow"></a>
### Indent error flow
<a id="TOC-IndentErrorFlow"></a>
Handle errors before proceeding with the rest of your code. This improves the
readability of the code by enabling the reader to find the normal path quickly.
This same logic applies to any block which tests a condition then ends in a
terminal condition (e.g., `return`, `panic`, `log.Fatal`).
Code that runs if the terminal condition is not met should appear after the `if`
block, and should not be indented in an `else` clause.
```go
// Good:
if err != nil {
// error handling
return // or continue, etc.
}
// normal code
```
```go
// Bad:
if err != nil {
// error handling
} else {
// normal code that looks abnormal due to indentation
}
```
> **Tip:** If you are using a variable for more than a few lines of code, it is
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 198k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |