PY
GO

Python to Go

10 lessons

Progress0%
1Variables & Types2Functions3Lists → Slices, Dicts → Maps4Classes → Structs5asyncio → Goroutines6Modules → Packages7Interfaces8Error Handling Patterns9Testing10Standard Library
All Mirror Courses
PY
GO
Standard Library
MirrorLesson 10 of 10
Lesson 10

Standard Library

Go stdlib vs Python's batteries included — strings, os, json, http

Introduction

In this lesson, you'll learn about standard library in Go. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
PY
From Python:

In Python, you're familiar with go stdlib vs python's batteries included — strings, os, json, http.

GO
In Go:

Go has its own approach to go stdlib vs python's batteries included — strings, os, json, http, which we'll explore step by step.

The Go Way

Let's see how Go handles this concept. Here's a typical example:

GO
Go Example
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "regexp"
    "strings"
    "time"
)

func main() {
    // strings package
    strings.Split("hello world", " ")     // ["hello","world"]
    strings.Join([]string{"a","b"}, ",")  // "a,b"
    strings.TrimSpace("  hi  ")           // "hi"
    strings.ToUpper("hello")              // "HELLO"

    // os package
    os.Getenv("HOME")
    os.ReadFile("file.txt")               // []byte, error
    os.WriteFile("out.txt", data, 0644)

    // JSON
    type Config struct {
        Key string `json:"key"`
        Val int    `json:"val"`
    }
    var cfg Config
    json.Unmarshal([]byte(`{"key":"x","val":1}`), &cfg)
    out, _ := json.MarshalIndent(cfg, "", "  ")

    // HTTP client
    resp, err := http.Get("https://example.com")
    if err != nil { panic(err) }
    defer resp.Body.Close()
    // io.ReadAll(resp.Body)

    // Regex
    re := regexp.MustCompile(`\d+`)
    re.FindString("abc123")  // "123"
    re.FindAllString("1a2b3c", -1)  // ["1","2","3"]

    // Time
    now := time.Now()
    now.Format("2006-01-02")   // "YYYY-MM-DD" in Go's reference time!
    time.Since(start)
}

Comparing to Python

Here's how you might have written similar code in Python:

PY
Python (What you know)
import os
import json
import re
import datetime
from pathlib import Path
from urllib.request import urlopen

# String ops
"hello world".split()    # ["hello","world"]
",".join(["a","b","c"])  # "a,b,c"
"  hi  ".strip()          # "hi"

# OS/file
os.getenv("HOME")
os.path.join("dir", "file.txt")
Path("dir/file.txt").read_text()

# JSON
data = json.loads('{"k":1}')
json.dumps(data, indent=2)

# HTTP
with urlopen("http://example.com") as r:
    html = r.read().decode()

# Regex
import re
m = re.search(r"\d+", "abc123")
m.group()  # "123"

# Date
from datetime import datetime
now = datetime.now()
now.strftime("%Y-%m-%d")
Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

GO
In Go:

Go time format uses reference time '2006-01-02 15:04:05' — not strftime codes

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

GO
In Go:

regexp.MustCompile panics on bad patterns — use Compile for safe compile

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

GO
In Go:

http.Get is in stdlib — no requests package needed for basic HTTP

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

GO
In Go:

JSON uses struct tags json:"name" for field mapping

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

GO
In Go:

os.ReadFile/WriteFile replace Python's open() for simple cases

Step-by-Step Breakdown

1. strings Package

All string operations are in the 'strings' package. Since Go strings are immutable, all functions return new strings.

PY
Python
"a,b,c".split(",")
",".join(["a","b"])
GO
Go
strings.Split("a,b,c", ",")
strings.Join([]string{"a","b"}, ",")

2. Time Formatting

Go uses a reference time (Jan 2, 2006 = 01/02/06) instead of strftime codes. Memorize: 2006-01-02 15:04:05.

PY
Python
datetime.now().strftime("%Y-%m-%d")
GO
Go
time.Now().Format("2006-01-02")     // YYYY-MM-DD
time.Now().Format("15:04:05")        // HH:MM:SS
time.Now().Format(time.RFC3339)      // ISO 8601
Common Pitfall
Go's reference time is always 2006-01-02 15:04:05 — not arbitrary numbers. Use the exact reference values.

3. HTTP Client

net/http includes a full HTTP client. For production use, set a timeout on the client.

PY
Python
import requests
resp = requests.get(url)
resp.json()
GO
Go
client := &http.Client{Timeout: 10*time.Second}
resp, err := client.Get(url)
defer resp.Body.Close()
var result MyType
json.NewDecoder(resp.Body).Decode(&result)

4. JSON with Struct Tags

Go's encoding/json uses struct field tags to map JSON keys to struct fields. Unexported fields are ignored.

PY
Python
data = json.loads(text)  # dict, no schema
print(data["name"])
GO
Go
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age,omitempty"`
}
var u User
json.Unmarshal([]byte(text), &u)
fmt.Println(u.Name)
Rule of Thumb
Use omitempty tag on optional fields to skip zero values in JSON output.

Common Mistakes

When coming from Python, developers often make these mistakes:

  • Go time format uses reference time '2006-01-02 15:04:05' — not strftime codes
  • regexp.MustCompile panics on bad patterns — use Compile for safe compile
  • http.Get is in stdlib — no requests package needed for basic HTTP
Common Pitfall
Don't assume Go works exactly like Python. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • strings: Split, Join, ToUpper, TrimSpace, Contains, Replace — all return new strings
  • Go time format uses reference time: 2006-01-02 15:04:05 (not strftime codes)
  • net/http client is production-ready stdlib; set Timeout on the client
  • JSON uses struct tags json:"name" for mapping; Unmarshal into typed structs
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your Python code in Go to practice these concepts.
PreviousFinish