Free Code Examples & Snippets
Browse hand-picked, runnable code examples for JavaScript, TypeScript, Python, and Go. Each example can be tested immediately in the DevsCurry online playground.
Array map, filter, and reduce in JavaScript
Transform, filter, and aggregate arrays using functional JavaScript methods.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const doubledEvens = numbers.filter((n) => n % 2 === 0).map((n) => n * 2);
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log('Doubled evens:', doubledEvens);
console.log('Total sum:', sum);
Async / Await with Promises in JavaScript
Handle concurrent asynchronous operations using async/await and Promise.all.
function delay(ms, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
async function fetchUserData() {
console.log('Fetching user data...');
const [profile, settings] = await Promise.all([
delay(200, { name: 'Alice', role: 'Engineer' }),
delay(100, { theme: 'dark', notifications: true }),
]);
console.log('Profile loaded:', profile);
console.log('Settings loaded:', settings);
}
fetchUserData();
Closures and Lexical Scope in JavaScript
Encapsulate private state and create factory functions using lexical closures.
function createCounter(initialValue = 0) {
let count = initialValue;
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count,
};
}
const counter = createCounter(10);
console.log('Increment:', counter.increment());
console.log('Increment again:', counter.increment());
console.log('Decrement:', counter.decrement());
console.log('Current value:', counter.getValue());
Debounce Function in JavaScript
Rate-limit high-frequency event handlers such as search inputs or window resizes.
function debounce(fn, delayMs) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delayMs);
};
}
const logSearch = debounce((query) => {
console.log('Searching API for:', query);
}, 300);
console.log('Typing rapid keystrokes...');
logSearch('r');
logSearch('re');
logSearch('react'); // Only this final call executes after 300ms
Deep Clone Objects in JavaScript
Deeply copy complex nested objects using structuredClone without mutating originals.
const original = {
name: 'DevsCurry',
stats: { stars: 120, tags: ['coding', 'playground'] },
createdAt: new Date(),
};
const copy = typeof structuredClone === 'function'
? structuredClone(original)
: JSON.parse(JSON.stringify(original));
copy.stats.tags.push('webassembly');
copy.name = 'DevsCurry Clone';
console.log('Original tags:', original.stats.tags);
console.log('Cloned tags:', copy.stats.tags);
console.log('Are nested objects separate:', original.stats !== copy.stats);
Destructuring and Spread Syntax in JavaScript
Unpack properties, merge configurations, and use rest parameters cleanly.
const user = { id: 101, username: 'dev_alex', role: 'admin', country: 'US' };
const { username, role, ...metadata } = user;
console.log('User:', username, `(${role})`);
console.log('Remaining metadata:', metadata);
const baseConfig = { theme: 'dark', fontSize: 14 };
const userConfig = { ...baseConfig, fontSize: 16, lineNumbers: true };
console.log('Merged config:', userConfig);
Event Emitter (Pub/Sub Pattern) in JavaScript
Implement a lightweight Publish/Subscribe event bus with listener subscriptions.
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
(this.events[event] = this.events[event] || []).push(listener);
return () => this.off(event, listener);
}
off(event, listener) {
if (!this.events[event]) return;
this.events[event] = this.events[event].filter((l) => l !== listener);
}
emit(event, ...args) {
(this.events[event] || []).forEach((listener) => listener(...args));
}
}
const bus = new EventEmitter();
const unsubscribe = bus.on('notify', (msg) => console.log('Notification received:', msg));
bus.emit('notify', 'Welcome to DevsCurry!');
unsubscribe();
bus.emit('notify', 'This will not log');
Function Currying in JavaScript
Transform multi-argument functions into sequential single-argument functions.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function (...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
};
}
const multiply = (a, b, c) => a * b * c;
const curriedMultiply = curry(multiply);
const double = curriedMultiply(2);
const doubleAndTriple = double(3);
console.log('Curried call 1:', curriedMultiply(2)(3)(4));
console.log('Curried call 2:', doubleAndTriple(5));
Proxy and Reflect (Reactivity) in JavaScript
Intercept property access, assignment, and mutations like modern reactive frameworks.
const target = { count: 0, text: 'Hello' };
const reactive = new Proxy(target, {
get(obj, prop, receiver) {
console.log(`[GET] ${String(prop)}:`, obj[prop]);
return Reflect.get(obj, prop, receiver);
},
set(obj, prop, value, receiver) {
console.log(`[SET] ${String(prop)} changed from ${obj[prop]} to ${value}`);
return Reflect.set(obj, prop, value, receiver);
},
});
reactive.count = 42;
console.log('Read count:', reactive.count);
Generators and Iterators in JavaScript
Produce lazy sequences and custom iterable streams using function* and yield.
function* fibonacciGenerator(limit = 6) {
let [prev, curr] = [0, 1];
for (let i = 0; i < limit; i++) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
const fib = fibonacciGenerator(6);
console.log('Generated sequence:');
for (const n of fib) {
console.log('->', n);
}
Memoization Function Cache in JavaScript
Cache expensive calculation results to speed up repeated function calls.
function memoize(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log(`[Cache Hit] for arguments: ${key}`);
return cache.get(key);
}
console.log(`[Computing...] for arguments: ${key}`);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const slowFactorial = memoize((n) => (n <= 1 ? 1 : n * slowFactorial(n - 1)));
console.log('Factorial 5:', slowFactorial(5));
console.log('Factorial 5 again:', slowFactorial(5));
console.log('Factorial 6:', slowFactorial(6));
ES6 Classes and Inheritance in JavaScript
Define object-oriented classes with constructor, methods, extends, and getters.
class Shape {
constructor(name) {
this.name = name;
}
describe() {
return `Shape: ${this.name}`;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super('Rectangle');
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const rect = new Rectangle(5, 8);
console.log(rect.describe());
console.log('Calculated Area:', rect.area);
Interfaces and Generics in TypeScript
Write type-safe, reusable functions constrained by interface boundaries.
interface Entity {
id: string | number;
}
function findById<T extends Entity>(items: T[], targetId: string | number): T | undefined {
return items.find((item) => item.id === targetId);
}
interface User extends Entity {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
];
console.log('Found user:', findById(users, 2));
Built-in Utility Types in TypeScript
Transform types using Partial, Pick, Omit, and Record utility types.
interface Article {
id: number;
title: string;
body: string;
author: string;
}
type ArticlePreview = Pick<Article, 'id' | 'title'>;
type NewArticle = Omit<Article, 'id'>;
type DraftArticle = Partial<Article>;
type ArticleCatalog = Record<string, ArticlePreview>;
const preview: ArticlePreview = { id: 1, title: 'Mastering TypeScript' };
console.log('Preview:', preview);
Discriminated Unions in TypeScript
Model exhaustive state machines and network states using tagged unions.
type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };
function renderState<T>(state: AsyncState<T>): string {
switch (state.status) {
case 'idle':
return 'Waiting to start...';
case 'loading':
return 'Loading data...';
case 'success':
return `Success: ${JSON.stringify(state.data)}`;
case 'error':
return `Error occurred: ${state.message}`;
}
}
console.log(renderState({ status: 'loading' }));
console.log(renderState({ status: 'success', data: { user: 'Alice' } }));
Type Narrowing and Type Guards in TypeScript
Refine union types safely using typeof, instanceof, and custom is type predicates.
interface Dog {
kind: 'dog';
bark(): void;
}
interface Cat {
kind: 'cat';
meow(): void;
}
type Pet = Dog | Cat;
function isDog(pet: Pet): pet is Dog {
return pet.kind === 'dog';
}
function speak(pet: Pet) {
if (isDog(pet)) {
pet.bark();
} else {
pet.meow();
}
}
const myDog: Dog = { kind: 'dog', bark: () => console.log('Woof woof!') };
speak(myDog);
keyof and typeof Operators in TypeScript
Extract property names and infer static types from existing JavaScript objects.
const appConfig = {
endpoint: 'https://api.devscurry.com',
timeout: 5000,
retries: 3,
};
type AppConfig = typeof appConfig;
type ConfigKey = keyof AppConfig;
function getOption<K extends ConfigKey>(key: K): AppConfig[K] {
return appConfig[key];
}
console.log('API Endpoint:', getOption('endpoint'));
console.log('Timeout (ms):', getOption('timeout'));
Mapped and Template Literal Types in TypeScript
Transform object keys dynamically and combine string literal types.
type ReadonlyNullable<T> = {
readonly [P in keyof T]: T[P] | null;
};
type EventName = 'click' | 'hover';
type EventHandler = `on${Capitalize<EventName>}`;
interface Point {
x: number;
y: number;
}
type SafePoint = ReadonlyNullable<Point>;
const p: SafePoint = { x: 10, y: null };
console.log('Safe point:', p);
const handlerName: EventHandler = 'onClick';
console.log('Event handler name:', handlerName);
Enums and Status Codes in TypeScript
Model fixed enumerations with numeric and string TypeScript enums.
enum StatusCode {
Ok = 200,
Created = 201,
BadRequest = 400,
NotFound = 404,
}
function handleResponse(code: StatusCode) {
if (code === StatusCode.Ok || code === StatusCode.Created) {
return 'Operation succeeded!';
}
return `Failed with status code: ${code}`;
}
console.log(handleResponse(StatusCode.Ok));
console.log(handleResponse(StatusCode.NotFound));
Conditional Types in TypeScript
Select types dynamically using the ternary-style T extends U ? X : Y syntax.
type IsString<T> = T extends string ? true : false;
type NonNullableType<T> = T extends null | undefined ? never : T;
type Mixed = string | number | null | undefined;
type Clean = NonNullableType<Mixed>;
function processValue<T>(val: T): IsString<T> {
return (typeof val === 'string') as IsString<T>;
}
console.log('Is string (text):', processValue('hello'));
console.log('Is string (number):', processValue(123));
The infer Keyword in TypeScript
Extract internal return types and promise resolutions within conditional types.
type AwaitedType<T> = T extends Promise<infer U> ? U : T;
type FunctionReturn<T> = T extends (...args: any[]) => infer R ? R : never;
function calculate() {
return { status: 'ok', score: 100 };
}
type CalcResult = FunctionReturn<typeof calculate>;
const res: CalcResult = { status: 'ok', score: 100 };
console.log('Inferred function return shape:', res);
The satisfies Operator in TypeScript
Validate an expression matches a type without widening or losing specific literals.
type RGB = [red: number, green: number, blue: number];
type Color = RGB | string;
const palette = {
primary: '#ff5722',
secondary: [33, 150, 243],
} satisfies Record<string, Color>;
// primary retains string methods because it was not widened to Color:
console.log('Upper hex:', palette.primary.toUpperCase());
console.log('RGB sum:', palette.secondary.reduce((a, b) => a + b, 0));
Abstract Classes and Polymorphism in TypeScript
Enforce structural contracts while sharing base method implementations across subclasses.
abstract class DatabaseService {
constructor(protected dbName: string) {}
connect(): void {
console.log(`Connected to database: ${this.dbName}`);
}
abstract query(sql: string): string[];
}
class PostgresService extends DatabaseService {
query(sql: string): string[] {
return [`Result for: "${sql}" on ${this.dbName}`];
}
}
const db = new PostgresService('production_db');
db.connect();
console.log(db.query('SELECT * FROM users;'));
Type-Safe Builder Pattern in TypeScript
Create fluent, chainable configuration builders with strict return types.
class RequestBuilder {
private url = '';
private method: 'GET' | 'POST' = 'GET';
private headers: Record<string, string> = {};
setUrl(url: string): this {
this.url = url;
return this;
}
setMethod(method: 'GET' | 'POST'): this {
this.method = method;
return this;
}
setHeader(key: string, value: string): this {
this.headers[key] = value;
return this;
}
build() {
return { url: this.url, method: this.method, headers: this.headers };
}
}
const request = new RequestBuilder()
.setUrl('https://api.devscurry.com/run')
.setMethod('POST')
.setHeader('Content-Type', 'application/json')
.build();
console.log('Built request configuration:', request);
List, Dict, and Set Comprehensions in Python
Build filtered and transformed lists, dictionaries, and sets in single concise expressions.
numbers = range(1, 11)
# List comprehension:
squares = [n * n for n in numbers if n % 2 == 0]
# Dict comprehension:
square_dict = {f"num_{n}": n * n for n in range(1, 6)}
# Set comprehension:
unique_lengths = {len(w) for w in ["apple", "banana", "pear", "apple"]}
print("Squares of evens:", squares)
print("Dictionary mapping:", square_dict)
print("Unique word lengths:", unique_lengths)
Function Decorators in Python
Create custom wrapper decorators to measure execution time, log calls, and wrap behavior.
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
duration = time.perf_counter() - start
print(f"[{func.__name__}] executed in {duration:.6f}s")
return result
return wrapper
@timer_decorator
def calculate_sum(n):
return sum(i * i for i in range(n))
total = calculate_sum(50000)
print("Total sum:", total)
Generators and yield in Python
Produce memory-efficient streaming sequences on the fly using generator functions.
def infinite_fibonacci(limit=8):
a, b = 0, 1
for _ in range(limit):
yield a
a, b = b, a + b
print("Streaming Fibonacci numbers:")
for num in infinite_fibonacci(8):
print("->", num)
Dataclasses (@dataclass) in Python
Generate clean, typed data container classes with automatic __init__ and __repr__.
from dataclasses import dataclass, field
@dataclass
class Product:
id: int
name: str
price: float
tags: list[str] = field(default_factory=list)
def discounted_price(self, percent: float) -> float:
return self.price * (1 - percent / 100)
item = Product(id=1, name="Mechanical Keyboard", price=120.0, tags=["hardware", "usb"])
print("Product dataclass:", item)
print("Discounted price (20% off):", item.discounted_price(20))
*args and **kwargs Variable Arguments in Python
Accept arbitrary positional and keyword arguments and forward them between functions.
def log_event(event_name, *tags, **metadata):
print(f"Event: {event_name}")
print(f"Tags ({len(tags)}): {', '.join(tags)}")
for key, value in metadata.items():
print(f" {key}: {value}")
log_event(
"user_signup",
"auth",
"marketing",
user_id=1042,
plan="pro",
timestamp="2026-09-09",
)
Context Managers (with Statement) in Python
Manage resources and guarantee cleanup using __enter__ and __exit__ methods.
class TimerContext:
def __enter__(self):
print("[Context] Resource locked / initialized.")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("[Context] Cleanup completed / resource released.")
return False
with TimerContext():
print("Doing work inside context manager...")
total = sum(range(1000))
print("Work completed:", total)
Dictionaries and Frequency Counting in Python
Use defaultdict and dictionary methods to aggregate and sort frequency counters.
from collections import defaultdict
votes = ["python", "go", "typescript", "python", "python", "go"]
counts = defaultdict(int)
for lang in votes:
counts[lang] += 1
sorted_votes = sorted(counts.items(), key=lambda x: x[1], reverse=True)
for lang, score in sorted_votes:
print(f"{lang.capitalize()}: {score} votes")
Lambda Functions and Custom Sorting in Python
Sort lists of dictionaries and objects with anonymous lambda key functions.
students = [
{"name": "Alice", "grade": 88, "age": 22},
{"name": "Bob", "grade": 95, "age": 20},
{"name": "Charlie", "grade": 88, "age": 25},
]
# Sort by grade descending, then age ascending
students_sorted = sorted(students, key=lambda s: (-s["grade"], s["age"]))
for s in students_sorted:
print(f"{s['name']}: Grade {s['grade']}, Age {s['age']}")
Classes and Dunder Magic Methods in Python
Implement object-oriented classes with __add__, __repr__, and __eq__ operator overloads.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
v1 = Vector(2, 3)
v2 = Vector(5, 7)
v3 = v1 + v2
print("Vector addition:", v3)
print("Equality check:", v3 == Vector(7, 10))
Itertools Combinations and Grouping in Python
Perform memory-efficient iteration with itertools chain, combinations, and groupby.
import itertools
# Chaining iterables:
combined = list(itertools.chain([1, 2], ["a", "b"]))
print("Chained:", combined)
# Generating unique 2-item combinations:
colors = ["red", "green", "blue"]
combos = list(itertools.combinations(colors, 2))
print("2-color combinations:", combos)
# Grouping contiguous elements:
numbers = [1, 1, 2, 3, 3, 3, 4]
grouped = {k: len(list(g)) for k, g in itertools.groupby(numbers)}
print("Group frequencies:", grouped)
Type Hints and typing Module in Python
Annotate Python functions and variables with Union, Optional, and Callable type hints.
from typing import Optional, Union, Callable
def transform(
value: Union[int, str],
formatter: Optional[Callable[[str], str]] = None,
) -> str:
text = str(value).strip()
if formatter:
return formatter(text)
return text.upper()
print(transform(" hello python "))
print(transform(42, formatter=lambda s: f"Result: {s}"))
Custom Exceptions and Error Flow in Python
Define domain-specific exception classes and handle try/except/else/finally control flow.
class ValidationError(Exception):
pass
def parse_age(age_str):
try:
age = int(age_str)
if age < 0 or age > 150:
raise ValidationError(f"Age {age} is out of realistic range.")
except ValueError as err:
print(f"[Error] Not a valid integer: {err}")
except ValidationError as err:
print(f"[Validation Failed] {err}")
else:
print(f"[Success] Valid age parsed: {age}")
finally:
print("Parsing attempt completed.\n")
parse_age("25")
parse_age("invalid")
parse_age("200")
Dynamic Slices and Operations in Go
Create, allocate, sub-slice, and append to dynamic arrays in Go.
package main
import "fmt"
func main() {
numbers := make([]int, 0, 5)
numbers = append(numbers, 10, 20, 30)
subSlice := numbers[1:3]
fmt.Println("Full Slice:", numbers)
fmt.Println("Sub Slice:", subSlice)
fmt.Printf("Length: %d, Capacity: %d\n", len(numbers), cap(numbers))
}
Goroutines and Channels in Go
Run concurrent functions in background goroutines and communicate through typed channels.
package main
import "fmt"
func worker(id int, ch chan<- string) {
ch <- fmt.Sprintf("Worker %d finished", id)
}
func main() {
ch := make(chan string, 3)
for i := 1; i <= 3; i++ {
go worker(i, ch)
}
for i := 1; i <= 3; i++ {
fmt.Println(<-ch)
}
}
The select Statement with Channels in Go
Multiplex communication across multiple channels with non-blocking selection.
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(50 * time.Millisecond)
ch1 <- "message from channel 1"
}()
go func() {
time.Sleep(100 * time.Millisecond)
ch2 <- "message from channel 2"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1:
fmt.Println("Received:", msg1)
case msg2 := <-ch2:
fmt.Println("Received:", msg2)
}
}
}
sync.WaitGroup for Concurrent Tasks in Go
Wait for a collection of concurrent goroutines to complete using sync.WaitGroup.
package main
import (
"fmt"
"sync"
)
func processTask(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Task %d completed\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 4; i++ {
wg.Add(1)
go processTask(i, &wg)
}
wg.Wait()
fmt.Println("All concurrent tasks finished!")
}
sync.Mutex for Thread-Safe State in Go
Prevent race conditions and protect shared state using mutual exclusion locks.
package main
import (
"fmt"
"sync"
)
type SafeCounter struct {
mu sync.Mutex
count int
}
func (c *SafeCounter) Increment(wg *sync.WaitGroup) {
defer wg.Done()
c.mu.Lock()
c.count++
c.mu.Unlock()
}
func main() {
counter := SafeCounter{}
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go counter.Increment(&wg)
}
wg.Wait()
fmt.Println("Final thread-safe count:", counter.count)
}
Interfaces and Type Assertions in Go
Define polymorphic contracts and safely inspect underlying concrete types.
package main
import "fmt"
type Greeter interface {
Greet() string
}
type User struct {
Name string
}
func (u User) Greet() string {
return fmt.Sprintf("Hello, I am %s", u.Name)
}
func printGreeting(g Greeter) {
fmt.Println(g.Greet())
if user, ok := g.(User); ok {
fmt.Println("Concrete user name was:", user.Name)
}
}
func main() {
u := User{Name: "Gopher"}
printGreeting(u)
}
Structs and Pointer Receivers in Go
Define structured objects and methods with value versus pointer receivers.
package main
import "fmt"
type Account struct {
Owner string
Balance float64
}
// Pointer receiver modifies the struct in place
func (a *Account) Deposit(amount float64) {
a.Balance += amount
}
// Value receiver operates on a copy
func (a Account) Summary() string {
return fmt.Sprintf("Account of %s: $%.2f", a.Owner, a.Balance)
}
func main() {
acc := &Account{Owner: "Alice", Balance: 100.0}
acc.Deposit(50.0)
fmt.Println(acc.Summary())
}
defer, panic, and recover in Go
Handle unexpected runtime panics and guarantee cleanup logic execution.
package main
import "fmt"
func safeDivide(a, b int) {
defer func() {
if r := recover(); r != nil {
fmt.Printf("[Recovered from panic]: %v\n", r)
}
}()
if b == 0 {
panic("division by zero is not allowed")
}
fmt.Printf("%d / %d = %d\n", a, b, a/b)
}
func main() {
safeDivide(10, 2)
safeDivide(10, 0)
fmt.Println("Application continued normally after panic recovery!")
}
Custom Error Handling and Wrapping in Go
Create sentinel errors, wrap context with %w, and check matches with errors.Is.
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("record not found")
func queryDatabase(id int) (string, error) {
if id <= 0 {
return "", fmt.Errorf("query error: %w", ErrNotFound)
}
return fmt.Sprintf("User#%d", id), nil
}
func main() {
_, err := queryDatabase(-1)
if err != nil {
fmt.Println("Returned error:", err)
if errors.Is(err, ErrNotFound) {
fmt.Println("Matched sentinel ErrNotFound!")
}
}
}
Maps and Safe Key Lookups in Go
Store key-value pairs, check key existence with the ok idiom, and delete entries.
package main
import "fmt"
func main() {
scores := map[string]int{
"Alice": 95,
"Bob": 82,
}
scores["Charlie"] = 88
score, ok := scores["Bob"]
fmt.Printf("Bob score: %d (found: %t)\n", score, ok)
delete(scores, "Charlie")
_, charlieOk := scores["Charlie"]
fmt.Println("Charlie found after deletion:", charlieOk)
}
context.Context with Timeout in Go
Propagate deadlines, cancel operations, and manage request lifecycles.
package main
import (
"context"
"fmt"
"time"
)
func executeTask(ctx context.Context) {
select {
case <-time.After(100 * time.Millisecond):
fmt.Println("Task completed!")
case <-ctx.Done():
fmt.Println("Task aborted:", ctx.Err())
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
executeTask(ctx)
}
JSON Serialization with Struct Tags in Go
Marshal and unmarshal JSON payloads with custom struct field tags.
package main
import (
"encoding/json"
"fmt"
)
type PackageInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Tags []string `json:"tags,omitempty"`
}
func main() {
pkg := PackageInfo{
Name: "devscurry-runner",
Version: "1.0.0",
Tags: []string{"go", "wasm", "playground"},
}
jsonData, err := json.MarshalIndent(pkg, "", " ")
if err != nil {
panic(err)
}
fmt.Println("Serialized JSON:")
fmt.Println(string(jsonData))
}