Code Playground
Collection of copy-paste ready Go code snippets
How to Use
- 1. Copy Code: Click the copy button on any code snippet
- 2. Run Locally: Paste into a .go file and run with
go run filename.go - 3. Experiment: Modify and explore the code
- 4. Learn: Check the tutorials for detailed explanations
Quick Reference Snippets
Hello World
Hello Worldgo
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}Read Command Line Arguments
Read Command Line Argumentsgo
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println("Arguments:", os.Args[1:])
}
}Read from User Input
Read from User Inputgo
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println("You entered:", text)
}Simple HTTP Server
Simple HTTP Servergo
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from %s!", r.URL.Path)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}JSON Encoding
JSON Encodinggo
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
p := Person{"Alice", 30}
data, _ := json.Marshal(p)
fmt.Println(string(data))
}Goroutine Example
Goroutine Examplego
package main
import (
"fmt"
"time"
)
func printNumbers(name string) {
for i := 1; i <= 3; i++ {
fmt.Printf("%s: %d\n", name, i)
time.Sleep(100 * time.Millisecond)
}
}
func main() {
go printNumbers("A")
go printNumbers("B")
time.Sleep(1 * time.Second)
}Channel Communication
Channel Communicationgo
package main
import "fmt"
func main() {
messages := make(chan string)
go func() {
messages <- "Hello"
messages <- "World"
}()
msg1 := <-messages
msg2 := <-messages
fmt.Println(msg1, msg2)
}File Writing
File Writinggo
package main
import (
"fmt"
"os"
)
func main() {
data := []byte("Hello, Go!\n")
err := os.WriteFile("output.txt", data, 0644)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println("File written successfully")
}Next Steps
Once you're comfortable with these snippets, explore the full course for:
- ✓In-depth tutorials with explanations
- ✓Progressive exercises from beginner to advanced
- ✓Real-world project implementations
- ✓Video tutorials for visual learning
Tip: Try combining these snippets to create more complex programs!