Skip to content

Archive / page 95

All articles

Every practical article from the Nalar archive, newest first.

Go Updated 02 Sep 2025 2 min read

Loops in Go: A Practical Guide with Examples

Go has only one looping keyword: for. That can look unusual if you come from a language with separate for, while, and do-while constructs, but Go’s for is flexible enough to cover the common looping patterns. 1. Basic for Loop for i := 0; i < 5; i++ { fmt.Println(i) } This is similar to a traditional loop in C, Java, or JavaScript: initialize a counter, continue while the condition is true, and run the post statement after each iteration.

Go Updated 02 Sep 2025 4 min read

Learning Interfaces in Go: Concepts, Examples, and Best Practices

Interfaces are one of Go’s most important abstraction tools. An interface describes behavior as a set of method signatures. A concrete type satisfies an interface implicitly simply by implementing the required methods—there is no separate implements declaration. What Is an Interface? An interface is a set of methods. For example: type Speaker interface { Speak() string } type Person struct { Name string } func (p Person) Speak() string { return "Hello, my name is " + p.Name } Because Person has the required Speak() string method, it satisfies Speaker:

Python Updated 02 Sep 2025 2 min read

How to Use a Global Variable Inside a Python Function

Python variables follow scope rules that determine where a name can be read or assigned. A module-level variable can be read inside a function, but assigning to that same name requires special handling. Reading a Global Variable A function can read a module-level variable without the global keyword: app_name = "Nalar" def print_app_name(): print(app_name) print_app_name() Because the function does not assign to app_name, Python resolves the name from the enclosing module scope.

Go Updated 02 Sep 2025 2 min read

How to Safely Convert a String to an Integer in Go

Numbers often arrive as strings from command-line arguments, form input, files, environment variables, or APIs. Before performing arithmetic, convert the text with Go’s strconv package and handle invalid input explicitly. 1. Use strconv.Atoi() for int Atoi is the simplest choice when you want a base-10 int: package main import ( "fmt" "strconv" ) func main() { str := "123" num, err := strconv.Atoi(str) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Number:", num) } Invalid input such as "12a" returns an error. Never assume external text is valid without checking it.

Python Updated 02 Sep 2025 2 min read

How to List Files in a Directory with Python

Listing files in a directory is a common Python task for automation, data processing, uploads, and filesystem utilities. The standard library provides several good approaches. 1. os.listdir() os.listdir() returns names for both files and subdirectories, so filter the results when you need only regular files: import os def list_files(directory): try: entries = os.listdir(directory) return [ name for name in entries if os.path.isfile(os.path.join(directory, name)) ] except FileNotFoundError: return [] 2. os.scandir() os.scandir() returns DirEntry objects that can expose file-type information efficiently:

Go Updated 02 Sep 2025 2 min read

How to Get a Slice of Map Keys in Go

Go maps store key-value pairs, but many tasks only need the keys—for example, to sort them, display them, compare sets, or feed them into another operation. Map iteration is intentionally unordered, so extracting keys into a slice is also the first step when you need a deterministic order. 1. Collect All Keys with range func getMapKeys(m map[string]int) []string { keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } return keys } func main() { myMap := map[string]int{ "apple": 1, "banana": 2, "cherry": 3, } keys := getMapKeys(myMap) fmt.Println("Keys:", keys) } Preallocating the slice with capacity len(m) avoids unnecessary growth while keys are appended.

Python Updated 02 Sep 2025 2 min read

How to Flatten a List of Lists in Python

Python lists can contain other lists, which is useful for representing grouped or nested data. When you need a single sequence instead, you can flatten the nested structure in several ways. 1. Flatten One Level with a List Comprehension For a list where every top-level item is another list: nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]] flat_list = [item for sublist in nested_list for item in sublist] print(flat_list) Output:

Go Updated 02 Sep 2025 2 min read

How to Create Enum-Like Types in Go

Go does not have a dedicated enum keyword like Java, C#, or TypeScript. Instead, enum-like values are usually modeled with a named type plus constants, often using iota to generate sequential values. 1. A Simple Enum-Like Constant Set with iota iota is a counter that starts at zero within a const block and increments for each constant specification: package main import "fmt" const ( Red = iota Green Blue ) func main() { fmt.Println("Red:", Red) fmt.Println("Green:", Green) fmt.Println("Blue:", Blue) } Output:

Go Updated 02 Sep 2025 2 min read

How to Check Whether a Map Contains a Key in Go

Go has a built-in idiom for checking whether a map contains a key. A map lookup can return both the stored value and a boolean indicating whether the key is present. Check a Key myMap := map[string]int{ "apple": 1, "banana": 2, "cherry": 3, } key := "banana" value, exists := myMap[key] if exists { fmt.Printf("Key '%s' exists with value %d\n", key, value) } else { fmt.Printf("Key '%s' does not exist\n", key) } The boolean is important because a missing key returns the value type’s zero value. Without the boolean, you cannot distinguish a missing key from a present key whose stored value happens to be zero.

Go Updated 02 Sep 2025 2 min read

How to Check Whether a File Exists in Go

Checking whether a file exists is a common task when working with configuration, local state, generated output, or other filesystem resources. Go’s os package provides the necessary APIs, but it is important to distinguish “does not exist” from other errors such as permission failures. 1. Check with os.Stat os.Stat returns file metadata when the path can be resolved: package main import ( "errors" "fmt" "os" ) func fileExists(filename string) (bool, error) { _, err := os.Stat(filename) if err == nil { return true, nil } if errors.Is(err, os.ErrNotExist) { return false, nil } return false, err } func main() { filename := "example.txt" exists, err := fileExists(filename) if err != nil { fmt.Println("Error:", err) return } if exists { fmt.Printf("File '%s' exists.\n", filename) } else { fmt.Printf("File '%s' does not exist.\n", filename) } } Returning an error prevents permission or I/O problems from being mistaken for a missing file.

Python Updated 02 Sep 2025 1 min read

How to Check for a Specific Key in a Python Dictionary

Python dictionaries store key-value pairs and provide efficient key lookup. Before reading an optional key, you may want to check whether it exists. 1. Use in The recommended approach is the membership operator: my_dict = {"name": "Alice", "age": 30, "city": "New York"} if "name" in my_dict: print("The key exists.") else: print("The key does not exist.") This checks keys directly and clearly expresses the intent.

Go Updated 07 Sep 2025 2 min read

Generate Random Strings in Go

Random strings are useful for temporary identifiers, test data, filenames, invitation codes, and security-sensitive tokens. Go offers different random-number sources, and choosing the correct one matters. 1. math/rand for Non-Security Uses For simulations, test fixtures, randomized UI behavior, or other cases where predictability is not a security problem, math/rand is appropriate. With modern Go, create an explicit generator when you need independent pseudo-random state: package main import ( "fmt" "math/rand" ) const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func GenerateRandomString(r *rand.Rand, length int) string { result := make([]byte, length) for i := range result { result[i] = alphabet[r.Intn(len(alphabet))] } return string(result) } func main() { r := rand.New(rand.NewSource(42)) fmt.Println(GenerateRandomString(r, 10)) } A fixed seed is useful for reproducible tests. Do not use math/rand for secrets, session tokens, password-reset tokens, or other authentication material.

Go Updated 07 Sep 2025 2 min read

Efficient String Concatenation in Go

String concatenation appears everywhere in Go programs: generating text, building paths, formatting reports, or assembling protocol messages. The best technique depends on how many pieces you are joining and how the data is already structured. 1. The + Operator For a small, fixed number of strings, + is clear and perfectly reasonable: str1 := "Hello, " str2 := "world!" result := str1 + str2 Avoid repeatedly growing a string with + inside a large loop, because each result is a new immutable string and repeated copying can become expensive.

Go Updated 02 Sep 2025 2 min read

Easy Ways to Convert an Integer to a String in Go

Converting an integer to a string is common when building output, logs, identifiers, URLs, or serialized data. Go provides several standard-library options depending on whether you need a simple decimal conversion or more control over formatting. 1. strconv.Itoa() For an int in base 10, strconv.Itoa is usually the clearest choice: package main import ( "fmt" "strconv" ) func main() { num := 42 str := strconv.Itoa(num) fmt.Println("String value:", str) } Itoa is equivalent to formatting the int as a base-10 integer.

Go Updated 02 Sep 2025 2 min read

Deploy a Go Web Server with systemd on Linux

When developing a small Go web server, it is common to run it manually with go run main.go. The problem is that the process stops when the terminal closes, and it will not automatically return after a server reboot. A better production setup is to run the application as a systemd service. That gives you automatic startup, monitoring, service management, and optional restart behavior after failures. 1. Create a Simple Go Web Server Start with a minimal HTTP server:

Python Updated 02 Sep 2025 2 min read

Check Whether a Key Exists in a Python Dictionary

Python dictionaries provide fast key-based lookup, and checking whether a key exists is a common operation. Use the in Operator The clearest and most idiomatic solution is: my_dict = {"name": "Alice", "age": 30, "city": "New York"} if "name" in my_dict: print("The key 'name' exists.") else: print("The key 'name' does not exist.") Membership tests on a dictionary check keys by default.

Python Updated 02 Sep 2025 2 min read

Catching Multiple Exceptions in Python

Python lets one except clause handle several exception types when they should receive the same response. This keeps error handling concise without hiding unrelated failures. Catch Several Exception Types Place the exception classes in a tuple: try: value = int(user_input) result = 100 / value except (ValueError, ZeroDivisionError) as exc: print(f"Invalid input: {exc}") ValueError handles non-numeric input, while ZeroDivisionError handles zero.

Web Development Updated 02 Sep 2025 3 min read

Building a Simple CRUD Application in Laravel: A Practical Guide

Building a CRUD application is one of the best ways to learn the core pieces of Laravel. In this guide, we will create a simple Post resource that supports Create, Read, Update, and Delete operations using Eloquent, resource routes, validation, and Blade views. 1. Create the Laravel Project Make sure Composer and a supported PHP version are installed, then run: composer create-project --prefer-dist laravel/laravel laravel-crud cd laravel-crud php artisan serve The development server is normally available at http://localhost:8000.

Web Development Updated 02 Sep 2025 3 min read

Building a Nested Category API in Laravel 11: A Practical Guide

Nested categories are common in e-commerce platforms, CMS applications, documentation systems, and other products that need hierarchical navigation. In Laravel, a self-referencing Eloquent relationship can model a category that belongs to a parent and has any number of children. This Laravel 11 example builds a small API for creating and reading category trees. 1. Create the Laravel Project composer create-project --prefer-dist laravel/laravel laravel-nested-categories cd laravel-nested-categories php artisan serve 2. Create the Category Model and Migration php artisan make:model Category -m Define the table in the generated migration:

Go Updated 02 Sep 2025 3 min read

Build a CRUD API with Go, Gin, MySQL, and GORM

This tutorial builds a small CRUD API with Go, the Gin web framework, MySQL, and GORM. It also uses godotenv for local development configuration. 1. Create the Project mkdir myapp cd myapp go mod init myapp 2. Install Dependencies go get github.com/gin-gonic/gin go get gorm.io/gorm go get gorm.io/driver/mysql go get github.com/joho/godotenv Run go mod tidy after adding your imports so the module file reflects the dependencies actually used by the application.

Go Updated 02 Sep 2025 3 min read

Arrays and Slices in Go: Add, Delete, Search, Update, Sort, and Filter

Go arrays and slices are straightforward once you understand their different roles. Arrays have a fixed length that is part of their type, while slices are flexible views over an underlying array and are the collection type used most often in application code. The following examples use a slice of structs: type Person struct { Name string Age int } people := []Person{ {Name: "Alice", Age: 30}, {Name: "Bob", Age: 25}, {Name: "John", Age: 20}, {Name: "Zara", Age: 35}, } 1. Add an Element Use append:

JavaScript Updated 07 Sep 2025 2 min read

Understanding the Differences Between pnpm, Yarn, npm, and Bun

JavaScript projects commonly use npm, Yarn, pnpm, or Bun to install dependencies and run package scripts. They all work with the npm package ecosystem, but they differ in installation strategy, lockfiles, workspace tooling, runtime integration, and compatibility details. npm npm ships with Node.js and is the most universal default. It supports lockfiles, workspaces, package scripts, and the standard npm registry with minimal setup. npm install npm run build Choose npm when you want the conventional Node.js toolchain and broad compatibility without adding another package manager.

JavaScript Updated 07 Sep 2025 2 min read

Create a Simple Static Web Server with `http-server`

When you need to test static HTML, CSS, JavaScript, images, or a generated site locally, the Node.js package http-server provides a small command-line server with minimal setup. Run It Without a Global Install If Node.js and npm are already installed, you can run the package with npx: npx http-server . The final . means “serve the current directory.” The command prints the local addresses and port it is using.

CSS Updated 02 Sep 2025 2 min read

Create a Hover Zoom Effect with Tailwind CSS

Small interactions can make a web page feel more polished. One simple example is a zoom effect when the pointer hovers over an image. With Tailwind CSS, you can build it with utility classes instead of writing a separate CSS rule. 1. HTML Structure Here is a basic example: <div class="relative"> <img src="https://picsum.photos/500/300.webp" alt="Image" class="hover:scale-125 transition-transform duration-300 ease-in-out"> </div> 2. What Do the Tailwind Classes Do? relative → gives the wrapper relative positioning. It does not create the zoom effect itself, but it is useful if you later add positioned overlays. hover:scale-125 → scales the image to 125% while it is hovered. transition-transform → animates changes to the transform property. duration-300 → makes the transition last 300 milliseconds. ease-in-out → starts and ends the transition gradually for a smoother feel. 3. Customize It Use a larger scale: