Member-only story
Exploring Go Features with JSON: iota, new, label, goto, and underscore
Exploring Go’s Hidden Gems: iota
, new
, goto
, Labels
, and Underscore
In this blog, we’ll dive deeper into Go’s lesser-known features — iota
, new
, labels, goto
, and the underscore (_
)—by incorporating JSON into our examples. JSON is a widely used data format, and combining it with these Go features will help demonstrate their practical applications.
1. iota with JSON: Enumerations for Configuration
iota
is perfect for defining enumerated constants, which can be useful when working with JSON configurations. For example, let’s define a set of status codes and unmarshal JSON data into a struct.
Example:
package main
import (
"encoding/json"
"fmt"
)
// Define status codes using iota
const (
StatusPending = iota // 0
StatusActive // 1
StatusCompleted // 2
)
// Config represents a configuration with a status
type Config struct {
Task string `json:"task"`
Status int `json:"status"`
}
func main() {
// JSON data
data := `{"task": "Write a blog", "status": 1}`
// Unmarshal JSON into Config struct
var config Config
err := json.Unmarshal([]byte(data), &config)
if err != nil {
fmt.Println("Error unmarshaling JSON:", err)
return
}
// Print the result…