開発
#python
convert-python-golang
Convert Python code to idiomatic Go. Use when migrating Python projects to Go, translating Python patterns to idiomatic Go, or refactoring Python codebases for performance and concurrency. Extends meta-convert-dev with Python-to-Go specific patterns.
DeepseekModel
キュレーション済みスキル
品質 良好 · 64
v1.0.0
取得
https://deepseekmodel.com/api/download.php?id=arustydev-agents-content-skills-convert-python-golang-skill-md&format=skill
ダウンロード .skill
標準形式。system_prompt と model_config を収録し、任意の Agent で利用可能
.skill ファイルの system_prompt フィールドの実際の内容。
name convert-python-golang description Convert Python code to idiomatic Go. Use when migrating Python projects to Go, translating Python patterns to idiomatic Go, or refactoring Python codebases for performance and concurrency. Extends meta-convert-dev with Python-to-Go specific patterns. Convert Python to Go Convert Python code to idiomatic Go. This skill extends meta-convert-dev with Python-to-Go specific type mappings, idiom translations, and tooling for transforming dynamic, interpreted Python code into static, compiled Go. This Skill Extends meta-convert-dev - Foundational conversion patterns (APTV workflow, testing strategies) For general concepts like the Analyze → Plan → Transform → Validate workflow, testing strategies, and common pitfalls, see the meta-skill first. This Skill Adds Type mappings : Python types → Go types (dynamic → static) Idiom translations : Python patterns → idiomatic Go Error handling : Exceptions → multiple return values with error Async patterns : asyncio → goroutines and channels Memory model : Python GC → Go GC (both garbage collected, different idioms) Type system : Duck typing → interfaces and struct embedding Build system : pip/uv → go modules This Skill Does NOT Cover General conversion methodology - see meta-convert-dev Python language fundamentals - see lang-python-dev Go language fundamentals - see lang-go-dev Reverse conversion (Go → Python) - see convert-golang-python Quick Reference Python Go Notes int int , int64 , big.Int Python has arbitrary precision float float64 IEEE 754 double precision bool bool Direct mapping str string Immutable UTF-8 strings bytes []byte Byte slices list[T] []T Slices (dynamic arrays) tuple struct{} or array Use struct for heterogeneous dict[K, V] map[K]V Hash maps set[T] map[T]bool or map[T]struct{} No built-in set type None nil (for pointers) or zero value Context-dependent Optional[T] *T (pointer) Pointer = nullable Union[T, U] interface{} or custom type Use type assertions def func(): func name() {} Functions async def func + goroutines No async/await syntax with defer Resource cleanup @decorator Function wrappers No decorator syntax class type + struct Composition over inheritance Exception error return value Multiple return values When Converting Code Analyze source thoroughly before writing target Map types first - create type equivalence table Handle arbitrary-precision integers - decide if int64 is enough or need big.Int Preserve semantics over syntax similarity Adopt Go idioms - don't write "Python code in Go syntax" Handle edge cases - None, exceptions, dynamic typing assumptions Test equivalence - same inputs → same outputs Type System Mapping Primitive Types Python Go Notes int int Platform-dependent (32 or 64-bit) int int64 Explicit 64-bit for large numbers int math/big.Int Python default - arbitrary precision float float64 IEEE 754 double precision bool bool Direct mapping str string Immutable UTF-8 strings bytes []byte Byte slice bytearray []byte Mutable byte slice None nil For pointers, slices, maps, channels None Zero value For value types (0, false, "") Critical Note on Integers : Python's int type has arbitrary precision and never overflows. Go integers are fixed-size and can overflow . Always validate range or use math/big.Int for Python-like behavior. Collection Types Python Go Notes list[T] []T Slice (dynamic array) tuple[T, U] struct{X T; Y U} Heterogeneous tuple → struct tuple[T, ...] []T Homogeneous tuple → slice dict[K, V] map[K]V Hash map set[T] map[T]bool Set as map keys set[T] map[T]struct{} Memory-efficient set frozenset[T] map[T]struct{} Go maps are mutable collections.deque container/list.List Doubly-linked list collections.OrderedDict Map iteration (Go 1.12+) Maps preserve insertion order in Go 1.12+ collections.defaultdict Map with check Use map access pattern collections.Counter map[T]int Count occurrences Composite Types Python Go Notes class (data) struct Data containers class (behavior) interface Behavior contracts @dataclass struct with literal Simple data structures typing.Protocol interface Duck typing → interfaces typing.TypedDict struct Named fields typing.NamedTuple struct Prefer struct enum.Enum const with iota Enumerated constants typing.Literal["a", "b"] const or custom type Literal types typing.Union[T, U] interface{} + type assertion Or custom type typing.Optional[T] *T (pointer) Pointer = nullable typing.Callable[[Args], Ret] func(Args) Ret Function types typing.Generic[T] Interfaces Go 1.18+ generics limited Type Annotations → Interfaces Python Go Notes def f(x: Iterable[T]) func f(x []T) Slice for most cases def f(x: Sequence[T]) func f(x []T) Slice for sequences def f(x: Mapping[K, V]) func f(x map[K]V) Map for mappings x: Any interface{} (or any ) Use sparingly Idiom Translation Pattern 1: None Handling (Optional Values) Python: # Optional chaining user = get_user(user_id) if user is not None : name = user.name else : name = "Anonymous" # Or with walrus operator if user := get_user(user_id): name = user.name Go: // Pointer nil check user := getUser(userID) var name string if user != nil { name = user.Name } else { name = "Anonymous" } // Or with early return user := getUser(userID) if user == nil { name = "Anonymous" } else { name = user.Name } Why this translation: Python uses None with truthiness; Go uses nil with explicit pointer checks Go's zero values provide defaults without needing None for primitives Go pointers are explicit about nullability Pattern 2: List Comprehensions → Slice Loops Python: # List comprehension squared_evens = [x * x for x in numbers if x % 2 == 0 ] # Generator expression total = sum (x * x for x in numbers if x % 2 == 0 ) Go: // Slice with filtering and mapping var squaredEvens [] int for _, x := range numbers { if x % 2 == 0 { squaredEvens = append (squaredEvens, x*x) } } // Manual aggregation total := 0 for _, x := range numbers { if x % 2 == 0 { total += x * x } } Why this translation: Go doesn't have list comprehensions; use explicit loops range loops are idiomatic for iteration append grows slices dynamically (similar to Python lists) Pattern 3: Dictionary Operations Python: # Get with default value = config.get( "timeout" , 30 ) # Setdefault pattern cache.setdefault(key, expensive_compute()) # Dictionary comprehension squared = {k: v * v for k, v in items.items()} Go: // Get with default value, ok := config[ "timeout" ] if !ok { value = 30 } // Check and set pattern if _, ok := cache[key]; !ok { cache[key] = expensiveCompute() } // Manual map building squared := make ( map [ string ] int ) for k, v := range items { squared[k] = v * v } Why this translation: Go's two-value map access ( value, ok := map[key] ) checks existence No built-in get method; use existence check pattern Explicit loops replace comprehensions Pattern 4: String Formatting Python: # f-strings message = f"User {user.name} has {count} items" # format method message = "User {} has {} items" . format (user.name, count) Go: // fmt.Sprintf (returns string) message := fmt.Sprintf( "User %s has %d items" , user.Name, count) // fmt.Printf (prints directly) fmt.Printf( "User %s has %d items\n" , user.Name, count) Why this translation: Go uses fmt package with C-style format specifiers %s for strings, %d for integers, %v for default format Type-safe at runtime (not compile-time like some languages) Pattern 5: Duck Typing → Interfaces Python: # Duck typing - if it has .read(), it's file-like def process_data ( file_like ): data = file_like.read() return parse(data) # Works with files, StringIO, BytesIO, etc. Go: // Interface definition type Reader interface { Read(p [] byte ) (n int , err error ) } // Function accepts interface func processData (r Reader) (Data, error ) { data, err := io.ReadAll(r) if err != nil { return Data{}, err } return parse(data) } // Works with *os.File, bytes.Buffer, strings.Reader, etc. Why this translation: Python relies on runtime duck typing; Go uses compile-time interfaces Go interfaces are implicit (no "implements" keyword) More type-safe but requires upfront interface definition Pattern 6: Context Managers → Defer Python: # Context manager for resource cleanup with open ( "file.txt" ) as f: data = f.read() # File automatically closed Go: // Defer for cleanup f, err := os.Open( "file.txt" ) if err != nil { return err } defer f.Close() // Guaranteed to run when function returns data, err := io.ReadAll(f) if err != nil { return err } Why this translation: Python's with guarantees cleanup via __exit__ Go's defer schedules function calls for later (LIFO order) Both ensure cleanup even with errors/returns Pattern 7: Decorators → Function Wrappers Python: from functools import wraps def log_calls ( func ): @wraps( func )
このスキルを起動するキーワード。クリックでコピーできます。
このスキルにはトリガーワードがありません。
ダウンロードした .skill に含まれるフィールド。
| フィールド | 説明 |
|---|---|
| format | フォーマット識別子(skill/v1) |
| skill_id | スキル固有 ID |
| name | スキル名 |
| version | バージョン |
| description | 説明 |
| category | カテゴリ(配列) |
| trigger_words | トリガーワード |
| tags | タグ |
| source | ソース |
| source_url | ソース URL(本ページ) |
| exported_at | エクスポート日時(ダウンロード毎) |
| system_prompt | システムプロンプト本文 |
| model_config | モデル設定:provider / model / temperature / max_tokens / top_p |
| examples | サンプル |
| install_guide | 各プラットフォームの導入説明(Coze / Dify / Claude / カスタム) |