Marshal and Unmarshal

In Go (Golang), marshal and unmarshal refer to the process of converting data between Go data structures and a byte stream, typically in a format like JSON, XML, or other serialized formats. These processes are commonly used for encoding and decoding data when working with external systems, such as APIs or file storage.

Marshal: The marshal process involves converting a Go data structure (like a struct, map, or slice) into a byte stream. This byte stream is usually in a format that can be easily transmitted or stored, such as JSON or XML. The encoding/json package in the standard library provides a Marshal function for encoding Go values as JSON.

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    person := Person{"John Doe", 30}
    jsonData, err := json.Marshal(person)
    if err != nil {
        fmt.Println("Error marshalling JSON:", err)
        return
    }
    fmt.Println(string(jsonData))
}

Unmarshal: The unmarshal process is the reverse: it involves converting a byte stream (in a serialized format like JSON) back into a Go data structure. The encoding/json package provides the Unmarshal function for this purpose.

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    jsonStr := `{"Name":"John Doe","Age":30}`
    var person Person
    err := json.Unmarshal([]byte(jsonStr), &person)
    if err != nil {
        fmt.Println("Error unmarshalling JSON:", err)
        return
    }
    fmt.Println(person)
}

In the Unmarshal function, the first argument is the byte slice containing the serialized data, and the second argument is a pointer to the variable where the unmarshaled data should be stored.