Home >Backend Development >Golang >Convert struct to byte golang

Convert struct to byte golang

WBOY
WBOYOriginal
2023-05-14 21:51:381059browse

In the Go language, structure (struct) is a very common type, which consists of multiple fields. In some cases, we need to convert a structure to a byte array, or a byte array to a structure. At this time, we can use some functions provided in the Go language to perform conversion.

  1. Convert structure to byte array

To convert structure to byte array, we can use the following method:

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

type User struct {
    Name string
    Age  int
}

func main() {
    user := User{Name: "张三", Age: 18}
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.BigEndian, user)
    if err != nil {
        fmt.Println("write error:", err)
        return
    }
    fmt.Println(buf.Bytes()) // [0 0 0 6 232 173 153 229 156 168 0 18]
}

In In the above code, we use the binary.Write function to convert the structure User into a byte array, where the buf variable is the buffer to be written.

  1. Convert byte array to structure

To convert byte array to structure, we can use the following method:

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

type User struct {
    Name string
    Age  int
}

func main() {
    data := []byte{0, 0, 0, 6, 232, 173, 153, 229, 156, 168, 0, 18}
    user := User{}
    buf := bytes.NewReader(data)
    err := binary.Read(buf, binary.BigEndian, &user)
    if err != nil {
        fmt.Println("read error:", err)
        return
    }
    fmt.Println(user) // {张三 18}
}

In In the above code, we use the binary.Read function to convert the byte array into the structure User, where the buf variable is the read buffer.

Summary

In the Go language, by using the functions in the encoding/binary package, we can easily convert the structure into a byte array or a word Convert section array to structure. This transformation is useful when programming on the web or interacting with other programming languages, allowing us to process structured data more efficiently.

The above is the detailed content of Convert struct to byte golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn