Sobes.tech
Junior — Middle

How can data structures be transformed into a format suitable for storage or transmission?

sobes.tech AI

Answer from AI

To convert data structures into a format suitable for storage or transmission (for example, over a network), serialization is commonly used in Go. The most common formats are JSON, XML, Gob.

For example, serializing a structure to JSON:

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    user := User{Name: "Anna", Age: 25}

    // Convert structure to JSON
    jsonData, err := json.Marshal(user)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(jsonData)) // {"name":"Anna","age":25}
}

For reverse conversion (deserialization), json.Unmarshal is used. Other formats work similarly.

Thus, serialization allows converting structures into a convenient format for storage or transmission, and then restoring them back.

How can data structures be transformed into a format… - sobes.tech