### Numscript Wrap-up Example with Metadata Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/reference/metadata.md Demonstrates a comprehensive Numscript example involving reading account metadata, sending monetary values, and setting both account and transaction metadata. It initializes variables, sends fees, distributes funds based on commission, and updates metadata for reference, fee, tax, and commission. ```numscript vars { account $order account $merchant = meta($order, "merchant") monetary $fee portion $commission string $ref } send $fee ( source = @orders:1234 destination = @platform:fees ) send [USD/2 *] ( source = @orders:1234 destination = { $commission to @platform:fees remaining to $merchant } ) set_account_meta($order, "reference", $ref) set_tx_meta("order_fee", $fee) set_tx_meta("tax", 20/100) set_tx_meta("commission", $commission) ``` -------------------------------- ### Go: Copying Slices on Output (Good vs. Bad) Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to safely return map data by creating a copy. The 'Bad' example returns the internal map directly, exposing it to external modification and potential data races. The 'Good' example creates a new map and copies the data, ensuring internal state integrity. ```go type Stats struct { mu sync.Mutex counters map[string]int } func (s *Stats) Snapshot() map[string]int { s.mu.Lock() defer s.mu.Unlock() result := make(map[string]int, len(s.counters)) for k, v := range s.counters { result[k] = v } return result } // Snapshot is now a copy. snapshot := stats.Snapshot() ``` -------------------------------- ### Start enums at one in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to initialize enumerations in Go, suggesting that enum values should typically start from one rather than zero. This practice avoids confusion with the default zero value of variables, unless the zero value represents a desired default behavior. ```go type Operation int const ( Add Operation = iota Subtract Multiply ) // Add=0, Subtract=1, Multiply=2 ``` ```go type Operation int const ( Add Operation = iota + 1 Subtract Multiply ) // Add=1, Subtract=2, Multiply=3 ``` ```go type LogOutput int const ( LogToStdout LogOutput = iota LogToFile LogToRemote ) // LogToStdout=0, LogToFile=1, LogToRemote=2 ``` -------------------------------- ### Handle Exit in Main with fmt.Fprintln and os.Exit - Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md A Go example demonstrating how to handle errors returned from a function and print them to stderr before exiting with a non-zero status code using os.Exit. ```go func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` -------------------------------- ### Refactor Initialization Logic from init() Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Illustrates how to refactor initialization logic out of the `init()` function in Go. This improves determinism, testability, and avoids dependencies on global state or I/O operations. Examples show direct assignment or helper functions. ```go type Foo struct { // ... } var _defaultFoo Foo func init() { _defaultFoo = Foo{ // ... } } ``` ```go var _defaultFoo = Foo{ // ... } // or, better, for testability: var _defaultFoo = defaultFoo() func defaultFoo() Foo { return Foo{ // ... } } ``` ```go type Config struct { // ... } var _config Config func init() { // Bad: based on current directory cwd, _ := os.Getwd() // Bad: I/O raw, _ := os.ReadFile( path.Join(cwd, "config", "config.yaml"), ) yaml.Unmarshal(raw, &_config) } ``` ```go type Config struct { // ... } func loadConfig() Config { cwd, err := os.Getwd() // handle err raw, err := os.ReadFile( path.Join(cwd, "config", "config.yaml"), ) // handle err var config Config yaml.Unmarshal(raw, &config) return config } ``` -------------------------------- ### Go Enum: Start Non-Zero with Iota Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/enum-start.md Demonstrates the recommended Go pattern for creating enumerations that start from a non-zero value using `iota`. This avoids the default zero value for the first constant, which can lead to unexpected behavior. ```go type Operation int const ( Add Operation = iota + 1 Subtract Multiply ) // Add=1, Subtract=2, Multiply=3 ``` -------------------------------- ### Go: Load configuration safely Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/init.md Illustrates how to load configuration in Go without relying on init(). The 'Good' example uses a dedicated function to handle file I/O and unmarshalling, making the code more explicit and testable. ```go type Config struct { // ... } func loadConfig() Config { cwd, err := os.Getwd() // handle err raw, err := os.ReadFile( path.Join(cwd, "config", "config.yaml"), ) // handle err var config Config yaml.Unmarshal(raw, &config) return config } ``` -------------------------------- ### Install Numscript CLI using golang toolchain Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/SKILL.md Installs the Numscript CLI using the Go toolchain. This method is suitable for developers working within the Go ecosystem and requires the Go environment to be set up. ```bash go get github.com/direktly/numscript ``` -------------------------------- ### Numscript Specs Balances Precondition Example (JSON) Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md This JSON example shows how to define initial account 'balances' as preconditions for Numscript tests. It includes balances for 'alice' and 'bob' with specific assets and amounts, setting up the initial state for the test execution. ```json { "balances": { "alice": { "USD/2" : 200 }, "bob": { "USD/2" : -42 }, } } ``` -------------------------------- ### Go: Exit program using os.Exit or log.Fatal* in main() Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/exit-main.md Demonstrates the correct and incorrect ways to handle program exits in Go. The 'Bad' example shows functions exiting directly, while the 'Good' example illustrates returning errors for proper control flow and testability. This pattern is crucial for managing program termination gracefully. ```go func main() { body := readFile(path) fmt.Println(body) } func readFile(path string) string { f, err := os.Open(path) if err != nil { log.Fatal(err) } b, err := io.ReadAll(f) if err != nil { log.Fatal(err) } return string(b) } ``` ```go func main() { body, err := readFile(path) if err != nil { log.Fatal(err) } fmt.Println(body) } func readFile(path string) (string, error) { f, err := os.Open(path) if err != nil { return "", err } b, err := io.ReadAll(f) if err != nil { return "", err } return string(b), nil } ``` -------------------------------- ### Go Function Ordering: Good Example Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/function-order.md Demonstrates the recommended approach for organizing Go code, placing type definitions first, followed by constructors, receiver methods, and finally utility functions. ```go type something struct{ ... } func newSomething() *something { return &something{} } func (s *something) Cost() { return calcCost(s.weights) } func (s *something) Stop() {...} func calcCost(n []int) int {...} ``` -------------------------------- ### Numscript Metadata Structure Examples Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/reference/metadata.md Illustrates the structure of metadata values in Numscript for various data types including number, string, asset, monetary, account, and portion. Each example shows a JSON object with a type and value key. ```json { "amount": { "type": "number", "value": 1000 } } ``` ```json { "reference": { "type": "string", "value": "82HHON80ILP" } } ``` ```json { "currency": { "type": "asset", "value": "USD/2" } } ``` ```json { "currency": { "type": "asset", "value": "USD/2" } } ``` ```json { "merchant": { "type": "account", "value": "platform:merchant" } } ``` ```json { "commission": { "type": "portion", "value": "15.5%" } } ``` -------------------------------- ### Numscript Run Input JSON Example Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/SKILL.md An example JSON file used as input for running a Numscript script. It defines the 'amt' variable and the initial balance for the 'alice' account, which are used during script execution. ```json { "variables": { "amt": "USD/2 100" }, "balances": { "alice": { "USD/2": 9999 } } } ``` -------------------------------- ### Go Variable Declaration: Bad Example Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md An example of a less idiomatic way to declare a variable in Go. Using `var` when a short variable declaration (`:=`) would be more direct for assigning an initial value. ```go var s = "foo" ``` -------------------------------- ### Install Agent Skills using npm Source: https://github.com/direkthq/skills/blob/main/README.md This command installs the Direkt AI agent skills package using npm. It makes a collection of pre-built skills available to your AI agent for various tasks. ```bash npx add-skill direktly/agent-skills ``` -------------------------------- ### Go Declaring Empty Slices: Bad Example Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates an less clear way to initialize an empty slice in Go. Explicitly declaring an empty slice using `[]int{}` can be less readable than using `var` and letting it default to a nil slice. ```go filtered := []int{} for _, v := range list { if v > 10 { filtered = append(filtered, v) } } ``` -------------------------------- ### Numscript Test Case Example Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md This JSON example demonstrates a Numscript test case. It includes schema definition, variable and balance preconditions, and two test cases with descriptions ('it') and expected postings. This illustrates how to define inputs and expected outputs for Numscript tests. ```json { "$schema": "https://raw.githubusercontent.com/direkly/numscript/specs.schema.json", "variables": { "source": "alice", "destination": "bob" }, "balances": { "alice": { "EUR/2": 500 } }, "testCases": [ { "it": "sends all the available balance when it doesn't exceed the cap and @alice has enough balance", "variables": { "cap": "EUR/2 9999" }, "expect.postings": [ { "source": "alice", "destination": "bob", "amount": 500, "asset": "EUR/2" } ] }, { "it": "caps the sent amt to $cap when lower than available balance", "variables": { "cap": "EUR/2 10" }, "expect.postings": [ { "source": "alice", "destination": "bob", "amount": 10, "asset": "EUR/2" } ] } ] } ``` -------------------------------- ### Comparing Time Instants with time.Time Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/time.md Compares the current time instant with start and stop times using the Before and Equal methods of time.Time. This is the recommended approach over using integer comparisons for time values. ```go func isActive(now, start, stop time.Time) bool { return (start.Before(now) || start.Equal(now)) && now.Before(stop) } ``` -------------------------------- ### Numscript Transaction Example Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/SKILL.md A Numscript example demonstrating sending USD through multiple accounts and splitting the final amount. This script models a financial transaction with clear source, destination, amount, and asset denominations. ```numscript send [USD/2 599] ( source = @world destination = @payments:001 ) send [USD/2 599] ( source = @payments:001 destination = @rides:0234 ) send [USD/2 599] ( source = @rides:0234 destination = { 85% to @drivers:042 remaining to { 10% to @charity remaining to @platform:fees } } ) ``` -------------------------------- ### Optimize String to Byte Conversion in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/string-byte-slice.md Demonstrates the performance difference between repeatedly converting a string to a byte slice and converting it once before a loop. The 'Good' example shows the optimized approach, resulting in a substantial performance gain. ```go for i := 0; i < b.N; i++ { w.Write([]byte("Hello world")) } ``` ```go data := []byte("Hello world") for i := 0; i < b.N; i++ { w.Write(data) } ``` -------------------------------- ### Go Function Ordering: Bad Example Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/function-order.md Illustrates a common but discouraged way of ordering functions in a Go file, where type definitions and constructors are interspersed with methods and utility functions. ```go func (s *something) Cost() { return calcCost(s.weights) } type something struct{ ... } func calcCost(n []int) int {...} func (s *something) Stop() {...} func newSomething() *something { return &something{} } ``` -------------------------------- ### Numscript Run Output Example Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/SKILL.md The output displayed after running a Numscript script with provided inputs. It shows the resulting transaction postings in a tabular format, detailing the source, destination, asset, and amount. ```text Postings: | Source | Destination | Asset | Amount | | alice | world | USD/2 | 100 | ``` -------------------------------- ### Go: Initialize struct with default values Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/init.md Demonstrates initializing a struct with default values in Go. The 'Good' example shows direct assignment or using a factory function for better testability, avoiding the use of init(). ```go type Foo struct { // ... } var _defaultFoo = Foo{ // ... } // or, better, for testability: var _defaultFoo = defaultFoo() func defaultFoo() Foo { return Foo{ // ... } } ``` -------------------------------- ### Design Domain Entities in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-architecture/SKILL.md Provides examples of designing domain entities in Go, illustrating the structure for an e-commerce order and a generic entity. Includes factory functions for creating new instances. ```go // Example for an e-commerce domain type Order struct { ID uuid.UUID CreatedAt time.Time UpdatedAt time.Time CustomerID uuid.UUID Items []OrderItem Status OrderStatus Total Money } func NewOrder(customerID uuid.UUID) *Order { return &Order{ ID: uuid.New(), CreatedAt: time.Now(), UpdatedAt: time.Now(), CustomerID: customerID, Status: OrderStatusPending, Items: []OrderItem{}, } } func (o *Order) AddItem(product Product, quantity int) error { // Business logic for adding items // Validate quantity, calculate prices, etc. } ``` ```go func NewEntity(businessAttribute string) *Entity { return &Entity{ ID: uuid.New(), CreatedAt: time.Now(), UpdatedAt: time.Now(), BusinessAttribute: businessAttribute, } } ``` -------------------------------- ### Go: Create Buffered Channel with Size 64 Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/channel-size.md This Go code snippet demonstrates creating a buffered channel with a capacity of 64 elements. It is presented as a 'bad' example, suggesting that larger buffer sizes should be avoided or carefully scrutinized. ```go // Ought to be enough for anybody! c := make(chan int, 64) ``` -------------------------------- ### Go Enum: Incorrect Start from Zero Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/enum-start.md Shows an example of a less preferred way to define enums in Go where the first value defaults to zero. This can be problematic if zero is not an intended distinct value for the enumeration. ```go type Operation int const ( Add Operation = iota Subtract Multiply ) // Add=0, Subtract=1, Multiply=2 ``` -------------------------------- ### Specify Map Capacity Hints (Go) Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Shows how to provide a capacity hint when initializing a map using `make()`. This helps pre-allocate memory, reducing reallocations as elements are added. ```Go files, _ := os.ReadDir("./files") m := make(map[string]os.DirEntry) for _, f := range files { m[f.Name()] = f } ``` ```Go files, _ := os.ReadDir("./files") m := make(map[string]os.DirEntry, len(files)) for _, f := range files { m[f.Name()] = f } ``` -------------------------------- ### Go: Use t.Fatal Instead of Panic in Tests Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/panic.md Illustrates the preferred method for handling errors during test setup in Go. The 'Bad' example uses panic, which is discouraged. The 'Good' example uses `t.Fatal`, ensuring the test is marked as failed without causing an uncontrolled program exit. ```go // func TestFoo(t *testing.T) f, err := os.CreateTemp("", "test") if err != nil { panic("failed to set up test") } ``` ```go // func TestFoo(t *testing.T) f, err := os.CreateTemp("", "test") if err != nil { t.Fatal("failed to set up test") } ``` -------------------------------- ### Channel sizing recommendations in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Provides guidance on channel sizing in Go, recommending channels to be unbuffered (size 0) or have a size of one. Larger channel sizes require careful consideration regarding load, blocking, and potential fill-up scenarios. ```go // Ought to be enough for anybody! c := make(chan int, 64) ``` ```go // Size of one c := make(chan int, 1) // or // Unbuffered channel, size of zero c := make(chan int) ``` -------------------------------- ### Numscript Script Execution Result Example Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/reference/metadata.md Represents the execution result of a Numscript, showing the state of variables after the script has run. It details the values for 'order', 'fee', 'commission', and 'reference' within the script's variable scope. ```json { "script": { "vars": { "order": "orders:186HH78UH", "fee": { "amount": 1000, "asset": "USD/2" }, "commission": "15.5%", "reference": "108IUYGI" } } } ``` -------------------------------- ### Write Transaction Metadata in Numscript Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/reference/metadata.md Writes metadata to a transaction using the `set_tx_meta` statement. This statement accepts a string-type key and a value, which can be a variable or a literal. Examples show setting order fee, tax, and commission account. ```numscript set_tx_meta("order_fee", [USD/2 100]) set_tx_meta("tax", 20/100) set_tx_meta("collection_account", @platform:commission) set_tx_meta("commission", $commission) ``` -------------------------------- ### Go Enum: Using Zero Value as Default Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/enum-start.md Illustrates a scenario in Go where using the zero value for an enum is appropriate, typically when the zero value represents a desired default behavior. This example shows logging outputs. ```go type LogOutput int const ( LogToStdout LogOutput = iota LogToFile LogToRemote ) // LogToStdout=0, LogToFile=1, LogToRemote=2 ``` -------------------------------- ### Install Numscript CLI using curl Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/SKILL.md Installs the Numscript CLI for Mac and Unix systems using a curl command. This is a straightforward method for quick installation on compatible operating systems. ```bash curl -sSL https://numscript.io/install | sh ``` -------------------------------- ### Specify Slice Capacity Hints (Go) Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates using `make([]T, length, capacity)` to initialize a slice with a specific capacity. This ensures sufficient memory is allocated upfront, minimizing reallocations during `append` operations. ```Go for n := 0; n < b.N; n++ { data := make([]int, 0) for k := 0; k < size; k++{ data = append(data, k) } } ``` ```Go for n := 0; n < b.N; n++ { data := make([]int, 0, size) for k := 0; k < size; k++{ data = append(data, k) } } ``` -------------------------------- ### Initialize Go Maps with `make` or Literals Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Prefer `make` for initializing empty or programmatically populated maps, allowing for capacity hints. Use map literals for maps with a fixed set of elements at initialization time. This improves visual distinction and performance. ```go var ( // m1 is safe to read and write; // m2 will panic on writes. m1 = make(map[T1]T2) m2 map[T1]T2 ) ``` ```go m := map[T1]T2{ k1: v1, k2: v2, k3: v3, } ``` -------------------------------- ### Numscript Transaction Output Example Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/SKILL.md The JSON output representing the execution of the Numscript transaction example. It details the postings, including source, destination, asset, and amount for each value movement. ```json { "postings": [ { "source": "world", "destination": "payments:001", "amount": 599, "asset": "USD/2" }, { "source": "payments:001", "destination": "rides:0234", "amount": 599, "asset": "USD/2" }, { "source": "rides:0234", "destination": "drivers:042", "amount": 510, "asset": "USD/2" }, { "source": "rides:0234", "destination": "charity", "amount": 9, "asset": "USD/2" }, { "source": "rides:0234", "destination": "platform:fees", "amount": 80, "asset": "USD/2" } ] } ``` -------------------------------- ### Build and Test Go Project Source: https://github.com/direkthq/skills/blob/main/skills/mcp-builder/SKILL.md Commands to build and test a Go project using standard Go tools and MCP Inspector. Ensure the project compiles successfully and passes MCP Inspector checks for quality and compatibility. ```bash go build npx @modelcontextprotocol/inspector ``` -------------------------------- ### Implement Application Services in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-architecture/SKILL.md Demonstrates the implementation of an application service in Go, specifically an 'OrderService'. It shows dependency injection of repositories and the signature for a 'PlaceOrder' method. ```go type OrderService struct { orderRepo repositories.OrderRepository productRepo repositories.ProductRepository idempotencyRepo repositories.IdempotencyRepository } func (s *OrderService) PlaceOrder(cmd *PlaceOrderCommand) (*PlaceOrderResult, error) { // Implement idempotency check // Validate products exist // Create order // Calculate totals // Save order // Return result } ``` -------------------------------- ### Install Numscript CLI using npm Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/SKILL.md Installs the Numscript CLI globally for Node.js environments using npm. This command ensures the numscript command is available system-wide for Node.js projects. ```bash npm install -g numscript ``` -------------------------------- ### Use time.Time for time instants in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Explains the importance of using Go's `time.Time` type for representing specific points in time. It shows how to correctly compare, add, and subtract time using methods provided by `time.Time`, avoiding common pitfalls related to time calculations. ```go func isActive(now, start, stop int) bool { return start <= now && now < stop } ``` ```go func isActive(now, start, stop time.Time) bool { return (start.Before(now) || start.Equal(now)) && now.Before(stop) } ``` -------------------------------- ### Handling Time Duration in JSON without Direct Support Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates how to handle `time.Duration` in JSON when the `encoding/json` package does not directly support it. The 'Good' example shows embedding the unit (milliseconds) in the field name for clarity, contrasting with the 'Bad' example which lacks unit information. ```go // {"interval": 2} type Config struct { Interval int `json:"interval"` } ``` ```go // {"intervalMillis": 2000} type Config struct { IntervalMillis int `json:"intervalMillis"` } ``` -------------------------------- ### Go Struct Initialization: With Field Names Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/struct-field-key.md Demonstrates the recommended way to initialize Go structs using explicit field names. This improves code readability and prevents potential errors. It is enforced by `go vet`. ```go k := User{ FirstName: "John", LastName: "Doe", Admin: true, } ``` -------------------------------- ### Go: Bad Struct Embedding Example (Public Types) Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/struct-embed.md Shows an example of embedding a public type (`http.Client`) incorrectly. The embedded type's fields and methods are exposed directly, which might not be intended and can lead to unexpected behavior or API pollution. ```go type Client struct { version int http.Client } ``` -------------------------------- ### Handle Errors Gracefully in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates various strategies for handling errors returned by functions. Includes logging and returning, wrapping errors with context, and degrading gracefully when errors occur. It highlights the importance of handling each error only once to avoid excessive logging. ```go u, err := getUser(id) if err != nil { // BAD: See description log.Printf("Could not get user %q: %v", id, err) return err } ``` ```go u, err := getUser(id) if err != nil { return fmt.Errorf("get user %q: %w", id, err) } ``` ```go if err := emitMetrics(); err != nil { // Failure to write metrics should not // break the application. log.Printf("Could not emit metrics: %v", err) } ``` ```go tz, err := getUserTimeZone(id) if err != nil { if errors.Is(err, ErrUserNotFound) { // User doesn't exist. Use UTC. tz = time.UTC } else { return fmt.Errorf("get user %q: %w", id, err) } } ``` -------------------------------- ### Initializing Empty Maps with make() in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/map-init.md Demonstrates the preferred way to initialize empty maps in Go using `make()`. This approach makes initialization visually distinct from declaration and allows for easy addition of size hints later. The example shows a 'bad' way using `map[T1]T2{}` and a 'good' way using `make(map[T1]T2)`. Note that `m2 map[T1]T2` without initialization will panic on writes. ```go var ( // m1 is safe to read and write; // m2 will panic on writes. m1 = map[T1]T2{} m2 map[T1]T2 ) ``` ```go var ( // m1 is safe to read and write; // m2 will panic on writes. m1 = make(map[T1]T2) m2 map[T1]T2 ) ``` -------------------------------- ### Numscript Specs Precondition Merging Example (JSON) Source: https://github.com/direkthq/skills/blob/main/skills/numscript-guidelines/reference/numscript-specs-format.md This JSON example illustrates precondition merging in Numscript specs. It shows how inner 'testCase' preconditions override top-level ones. In this case, 'alice's EUR/2 balance is updated by the inner 'balances' object. ```json { "balances": { "alice": { "EUR/2": 100, "USD/2": 100 }, "bob": { "EUR/2": -2 } }, "testCases": [ { "it": "example specs", "balances": { "alice": { "EUR/2": 999 } } } ] } ``` -------------------------------- ### Embed Go Mutex Correctly in Structs (Go) Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/mutex-zero-value.md Shows how to correctly embed a sync.Mutex within a struct in Go. The 'Good' example uses a named mutex field, hiding it from the exported API, unlike the 'Bad' example which embeds sync.Mutex directly, exposing its methods. ```go type SMap struct { mu sync.Mutex data map[string]string } func NewSMap() *SMap { return &SMap{ data: make(map[string]string), } } func (m *SMap) Get(k string) string { m.mu.Lock() defer m.mu.Unlock() return m.data[k] } ``` -------------------------------- ### Go: Good Practice - Composing with AbstractList Struct Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Demonstrates the 'good' practice in Go of composing a concrete list with an AbstractList struct via delegation. This approach encapsulates the AbstractList, providing better control over the public API and allowing for easier evolution. ```go // ConcreteList is a list of entities. type ConcreteList struct { list *AbstractList } // Add adds an entity to the list. func (l *ConcreteList) Add(e Entity) { l.list.Add(e) } // Remove removes an entity from the list. func (l *ConcreteList) Remove(e Entity) { l.list.Remove(e) } ``` -------------------------------- ### Go: Avoid Panics, Return Errors for Function Failures Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/panic.md Demonstrates the difference between panicking on an error and returning an error in Go. The 'Bad' example uses panic for a missing argument, while the 'Good' example returns an error, allowing the caller to handle it gracefully. This prevents cascading failures. ```go func run(args []string) { if len(args) == 0 { panic("an argument is required") } // ... } func main() { run(os.Args[1:]) } ``` ```go func run(args []string) error { if len(args) == 0 { return errors.New("an argument is required") } // ... return nil } func main() { if err := run(os.Args[1:]); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` -------------------------------- ### Go: Good Practice - Composing with AbstractList Interface Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Presents the 'good' practice in Go of composing a concrete list with an AbstractList interface through delegation. This method encapsulates the interface, providing a clean separation and maximizing flexibility for future modifications to both the concrete list and the abstract interface. ```go // ConcreteList is a list of entities. type ConcreteList struct { list AbstractList } // Add adds an entity to the list. func (l *ConcreteList) Add(e Entity) { l.list.Add(e) } // Remove removes an entity from the list. func (l *ConcreteList) Remove(e Entity) { l.list.Remove(e) } ``` -------------------------------- ### Initialize Go Structs Omitting Zero Values Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/struct-field-zero.md Demonstrates initializing a Go struct by omitting fields with zero values (e.g., empty string, false). This reduces verbosity and relies on Go's default zero-value assignments for these fields. The 'Good' example shows a cleaner initialization compared to the 'Bad' example which explicitly sets zero values. ```go user := User{ FirstName: "John", LastName: "Doe", MiddleName: "", Admin: false, } ``` ```go user := User{ FirstName: "John", LastName: "Doe", } ``` -------------------------------- ### Initialize Go Mutex Correctly (Go) Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/mutex-zero-value.md Demonstrates the correct way to initialize a sync.Mutex in Go. The zero-value is valid and preferred over using 'new(sync.Mutex)'. This avoids unnecessary pointer indirection. ```go var mu sync.Mutex mu.Lock() ``` -------------------------------- ### Initialize Go Struct References with `&T{}` Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/AGENTS.md Use the `&T{}` syntax instead of `new(T)` for initializing struct references. This ensures consistency with struct initialization practices and leads to more readable code. ```go sptr := &T{Name: "bar"} ``` -------------------------------- ### Prefix Unexported Globals with _ in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/global-name.md This Go code snippet demonstrates the convention of prefixing unexported top-level constants with an underscore (_). This practice helps to clearly indicate that these are global symbols and prevents accidental shadowing or misuse in other files within the same package. The 'bad' example shows how a local variable can shadow a global one without a compile error, while the 'good' example illustrates the recommended naming convention. ```go // foo.go const ( defaultPort = 8080 defaultUser = "user" ) // bar.go func Bar() { defaultPort := 9090 ... fmt.Println("Default port", defaultPort) // We will not see a compile error if the first line of // Bar() is deleted. } ``` ```go // foo.go const ( _defaultPort = 8080 _defaultUser = "user" ) ``` -------------------------------- ### Implement Entity Repository in Go Source: https://github.com/direkthq/skills/blob/main/skills/go-architecture/SKILL.md Demonstrates the implementation of an entity repository using Go and SQLC. It includes a Create method that inserts an entity into the database and performs a read-after-write to ensure data consistency. Dependencies include the SQLC generated database queries and a validated entity struct. ```go type SqlcEntityRepository struct { queries *db.Queries } func (repo *SqlcEntityRepository) Create(entity *ValidatedEntity) (*Entity, error) { ctx := context.Background() dbEntity, err := repo.queries.CreateEntity(ctx, db.CreateEntityParams{ ID: entity.ID, Name: entity.Name, CreatedAt: timestamptzFromTime(entity.CreatedAt), UpdatedAt: timestamptzFromTime(entity.UpdatedAt), }) if err != nil { return nil, err } // Always read after write return repo.FindByID(dbEntity.ID) } ``` -------------------------------- ### Go: Single Test Case (Bad) Source: https://github.com/direkthq/skills/blob/main/skills/go-style-guide/rules/table-driven-tests.md An example of a non-idiomatic, single-scenario test in Go. This approach is less maintainable and harder to extend compared to table-driven tests. ```go func TestIsEmpty(t *testing.T) { if got := IsEmpty(""); got != true { t.Fatalf("got %v, want %v", got, true) } } ```