2024 Dec 3
As an ESL speaker, I was initially confused when I first encountered the term “marshaling”.
To marshal generally means to bring together and arrange things in an effective or organized way. For example, “She marshaled her thoughts before answering the question.” It’s also commonly used in a military context, as in “marshaling the troops,” which means positioning them in the proper order or rank 1
In computer science, marshaling refers to the process of converting the memory representation of an object into a data format suitable for storage or transmission. 2
In other words, it’s the process of converting data structures into standardized formats (like JSON), which is often used in HTTP requests.
Marshal Function definition:
func Marshal(v any) ([]byte, error)
json.Marshal Example:
package main
import (
"encoding/json"
"fmt"
)
func main() {
type Player struct {
string
Name string
Club int
Number }
:= Player{
player : "Kerem Akturkoglu",
Name: "SL Benfica",
Club: 17,
Number}
, err := json.Marshal(player)
jsonDataif err != nil {
.Println("error:", err)
fmtreturn
}
.Println(string(jsonData))
fmt// output: {"Name":"Kerem Akturkoglu","Club":"SL Benfica","Number":17}
}
On the other hand, unmarshaling is the process of taking encoded data in a specific format and converting it back into a Go value.
Unmarshal Function definition:
func Unmarshal(data []byte, v interface{}) error
json.Unmarshal Example:
package main
import (
"encoding/json"
"fmt"
)
func main() {
:= `{"Name":"Kerem Akturkoglu","Club":"SL Benfica","Number":17}`
data
type Player struct {
string `json:"Name"`
Name string `json:"Club"`
Club int `json:"Number"`
Number }
var player Player
:= json.Unmarshal([]byte(data), &player)
err if err != nil {
.Println("error:", err)
fmtreturn
}
.Printf("Name: %s, Club: %s, Number: %d\n",
fmt.Name, player.Club, player.Number)
player
// output: Name: Kerem Akturkoglu, Club: SL Benfica, Number: 17
}
xml.Marshal Example:
package main
import (
"encoding/xml"
"fmt"
)
func main() {
type Player struct {
string
Name string
Club int
Number }
:= Player{
player : "Kerem Akturkoglu",
Name: "SL Benfica",
Club: 17,
Number}
, err := xml.Marshal(player)
xmlDataif err != nil {
.Println("error:", err)
fmtreturn
}
.Println(string(xmlData))
fmt
// output:
// <Player><Name>Kerem Akturkoglu</Name><Club>SL Benfica</Club><Number>17</Number></Player>
}
xml.Unmarshal Example:
package main
import (
"encoding/xml"
"fmt"
)
func main() {
:= `<Player><Name>Kerem Akturkoglu</Name><Club>SL Benfica</Club><Number>17</Number></Player>`
data
type Player struct {
string `xml:"Name"`
Name string `xml:"Club"`
Club int `xml:"Number"`
Number }
var player Player
:= xml.Unmarshal([]byte(data), &player)
err if err != nil {
.Println("error:", err)
fmtreturn
}
.Printf("Name: %s, Club: %s, Number: %d\n",
fmt.Name, player.Club, player.Number)
player
// output: Name: Kerem Akturkoglu, Club: SL Benfica, Number: 17
}