Loading...
Loading...
Go function design patterns including multiple return values, file organization, signature formatting, and Printf conventions. Use when writing functions, organizing Go source files, or formatting function signatures.
npx skill4agent add cxuu/golang-skills go-functionsstructconstvarNewXxxnewXxxfunc (s *something) Cost() int {
return calcCost(s.weights)
}
type something struct{ ... }
func calcCost(n []int) int { ... }
func (s *something) Stop() { ... }
func newSomething() *something {
return &something{}
}type something struct{ ... }
func newSomething() *something {
return &something{}
}
func (s *something) Cost() int {
return calcCost(s.weights)
}
func (s *something) Stop() { ... }
func calcCost(n []int) int { ... }func (r *SomeType) SomeLongFunctionName(foo1, foo2, foo3 string,
foo4, foo5, foo6 int) {
foo7 := bar(foo1)
}func (r *SomeType) SomeLongFunctionName(
foo1, foo2, foo3 string,
foo4, foo5, foo6 int,
) {
foo7 := bar(foo1)
}// Good: factor out locals
local := helper(some, parameters, here)
result := foo.Call(list, of, parameters, local)// Bad
printInfo("foo", true, true)
// Good
printInfo("foo", true /* isLocal */, true /* done */)booltype Region int
const (
UnknownRegion Region = iota
Local
)
func printInfo(name string, region Region, status Status)// Bad: pointer to interface is almost always wrong
func process(r *io.Reader) { ... }
// Good: pass the interface value directly
func process(r io.Reader) { ... }%q%q// Good: %q makes boundaries and special chars visible
fmt.Printf("value %q looks like English text", someText)
// Bad: manually adding quotes
fmt.Printf("value \"%s\" looks like English text", someText)%qPrintfconstgo vet// Bad: variable format string — go vet can't check it
msg := "unexpected values %v, %v\n"
fmt.Printf(msg, 1, 2)
// Good: const format string — go vet can validate
const msg = "unexpected values %v, %v\n"
fmt.Printf(msg, 1, 2)fgo vet// Good: go vet checks Wrapf format strings by default
func Wrapf(err error, format string, args ...any) error
// Bad: go vet won't check Wrap's format string
func Wrap(err error, format string, args ...any) errorgo vet -printfuncs=wrapf,statusfgo-functions/references/FUNCTIONAL-OPTIONS.md| Topic | Rule |
|---|---|
| File ordering | Type -> constructor -> exported -> unexported -> utils |
| Signature wrapping | All args on own lines with trailing comma |
| Naked parameters | Add |
| Pointers to interfaces | Almost never needed; pass interfaces by value |
| Use for human-readable string output |
| Format string storage | Declare as |
| Printf function names | End with |