0
0
GoComparisonBeginner · 3 min read

Marshal vs Unmarshal in Go: Key Differences and Usage

In Go, Marshal converts Go data structures into JSON bytes, turning your data into a format for storage or transfer. Unmarshal does the opposite: it reads JSON bytes and fills Go data structures with that data.
⚖️

Quick Comparison

This table summarizes the main differences between Marshal and Unmarshal in Go.

AspectMarshalUnmarshal
PurposeConvert Go data to JSON bytesConvert JSON bytes to Go data
DirectionGo struct → JSONJSON → Go struct
Function Signaturefunc Marshal(v interface{}) ([]byte, error)func Unmarshal(data []byte, v interface{}) error
Common Use CasePrepare data for sending or savingRead data received or loaded
Error HandlingFails if Go data can't be encodedFails if JSON is invalid or mismatched
Output TypeReturns JSON byte sliceModifies Go variable via pointer
⚖️

Key Differences

Marshal is used when you want to take your Go data, like structs or maps, and turn it into JSON format. This is useful when you want to send data over the internet or save it in a file. It returns a slice of bytes that represent the JSON.

Unmarshal works the other way around. It takes JSON data in bytes and fills your Go variables with the information. You must pass a pointer to the variable you want to fill, so Go knows where to put the data.

Errors can happen in both: Marshal can fail if your data contains types that can't be converted to JSON, while Unmarshal can fail if the JSON is not valid or doesn't match the Go data structure you provide.

💻

Marshal Code Example

go
package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Alice", Age: 30}
	jsonData, err := json.Marshal(p)
	if err != nil {
		fmt.Println("Error marshaling:", err)
		return
	}
	fmt.Println(string(jsonData))
}
Output
{"Name":"Alice","Age":30}
↔️

Unmarshal Equivalent

go
package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	jsonData := []byte(`{"Name":"Alice","Age":30}`)
	var p Person
	err := json.Unmarshal(jsonData, &p)
	if err != nil {
		fmt.Println("Error unmarshaling:", err)
		return
	}
	fmt.Printf("Name: %s, Age: %d\n", p.Name, p.Age)
}
Output
Name: Alice, Age: 30
🎯

When to Use Which

Choose Marshal when you need to convert your Go data into JSON format for sending over a network, saving to a file, or logging. Use Unmarshal when you receive JSON data from an external source like an API or file and want to convert it into Go data structures to work with it in your program.

In short, Marshal is for encoding Go data to JSON, and Unmarshal is for decoding JSON back into Go data.

Key Takeaways

Marshal converts Go data into JSON bytes for output or storage.
Unmarshal reads JSON bytes and fills Go variables with that data.
Always pass a pointer to Unmarshal so it can modify your variable.
Handle errors from both functions to catch invalid data or types.
Use Marshal to send or save data, and Unmarshal to receive or load data.