go
БесплатноБез исполняемых скриптовНе проверенGo programming patterns and idioms
Об этом скилле
Go
Overview
Go programming patterns including concurrency, error handling, and idiomatic Go code.
Basic Patterns
Structs and Methods
package main
import (
"encoding/json"
"fmt"
"time"
)
// Struct definition
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
metadata map[string]interface{} // unexported (private)
}
// Constructor function
func NewUser(email, name string) *User {
return &User{
ID: generateID(),
Email: email,
Name: name,
CreatedAt: time.Now(),
metadata: make(map[string]interface{}),
}
}
// Value receiver (for read-only)
func (u User) FullName() string {
return u.Name
}
// Pointer receiver (for mutations or large structs)
func (u *User) SetMetadata(key string, value interface{}) {
u.metadata[key] = value
}
// Embedding (composition)
type Admin struct {
User // Embedded struct
Permissions []string
}
func (a *Admin) HasPermission(perm string) bool {
for _, p := range a.Permissions {
if p == perm {
return true
}
}
return false
}
Interfaces
// Interface definition
type Repository interface {
Find(id string) (*User, error)
FindAll() ([]*User, error)
Create(user *User) error
Update(user *User) error
Delete(id string) error
}
// Interface implementation (implicit)
type MemoryRepository struct {
users map[string]*User
}
func NewMemoryRepository() *MemoryRepository {
return &MemoryRepository{
users: make(map[string]*User),
}
}
func (r *MemoryRepository) Find(id string) (*User, error) {
user, ok := r.users[id]
if !ok {
return nil, ErrNotFound
}
return user, nil
}
func (r *MemoryRepository) Create(user *User) error {
r.users[user.ID] = user
return nil
}
// Compile-time interface check
var _ Repository = (*MemoryRepository)(nil)
// Empty interface (any type)
func PrintAny(v interface{}) {
fmt.Printf("%v\n", v)
}
// Type assertion
func ProcessValue(v interface{}) {
switch val := v.(type) {
case string:
fmt.Println("String:", val)
case int:
fmt.Println("Int:", val)
case *User:
fmt.Println("User:", val.Name)
default:
fmt.Println("Unknown type")
}
}
Error Handling
import (
"errors"
"fmt"
)
// Sentinel errors
var (
ErrNotFound = errors.New("not found")
ErrBadRequest = errors.New("bad request")
)
// Custom error type
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation error on %s: %s", e.Field, e.Message)
}
// Error wrapping
func GetUser(id string) (*User, error) {
user, err := repository.Find(id)
if err != nil {
return nil, fmt.Errorf("getting user %s: %w", id, err)
}
return user, nil
}
// Error checking
func ProcessUser(id string) error {
user, err := GetUser(id)
if err != nil {
if errors.Is(err, ErrNotFound) {
return fmt.Errorf("user not found: %s", id)
}
var validationErr *ValidationError
if errors.As(err, &validationErr) {
return fmt.Errorf("validation failed: %s", validationErr.Field)
}
return err
}
// Process user...
return nil
}
// Multi-error handling
type MultiError struct {
Errors []error
}
func (m *MultiError) Error() string {
var msgs []string
for _, err := range m.Errors {
msgs = append(msgs, err.Error())
}
return strings.Join(msgs, "; ")
}
func (m *MultiError) Add(err error) {
if err != nil {
m.Errors = append(m.Errors, err)
}
}
func (m *MultiError) HasErrors() bool {
return len(m.Errors) > 0
}
Concurrency
Goroutines and Channels
// Basic goroutine
func main() {
go func() {
fmt.Println("Hello from goroutine")
}()
time.Sleep(100 * time.Millisecond)
}
// Channel basics
func worker(jobs <-chan int, results chan<- int) {
for job := range jobs {
results <- job * 2
}
}
func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)
// Start workers
for w := 0; w < 3; w++ {
go worker(jobs, results)
}
// Send jobs
for j := 0; j < 9; j++ {
jobs <- j
}
close(jobs)
// Collect results
for r := 0; r < 9; r++ {
fmt.Println(<-results)
}
}
// Select for multiple channels
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(100 * time.Millisecond)
ch1 <- "one"
}()
go func() {
time.Sleep(200 * time.Millisecond)
ch2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1:
fmt.Println("Received:", msg1)
case msg2 := <-ch2:
fmt.Println("Received:", msg2)
case <-time.After(500 * time.Millisecond):
fmt.Println("Timeout")
}
}
}
Concurrency Patterns
import (
"context"
"sync"
)
// Worker pool
type WorkerPool struct {
numWorkers int
jobs chan func()
wg sync.WaitGroup
}
func NewWorkerPool(numWorkers int) *WorkerPool {
pool := &WorkerPool{
numWorkers: numWorkers,
jobs: make(chan func(), numWorkers*2),
}
pool.Start()
Установить go в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл go?
Go programming patterns and idioms
Как установить скилл go?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл go запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic