Home > Backend Development > Golang > Copy bytes into struct fields using reflection

Copy bytes into struct fields using reflection

WBOY
Release: 2024-02-09 09:00:35
forward
551 people have browsed it

Copy bytes into struct fields using reflection

php editor strawberry introduction: In programming, sometimes we need to copy byte data into the fields of the structure. This process can be achieved by using reflection. Reflection is a powerful tool for inspecting and manipulating code structures at runtime. Through reflection, we can obtain the field information of the structure and copy the byte data into the structure according to the type and order of the fields to realize data conversion and assignment. This approach can bring us convenience and flexibility, allowing us to process byte data more efficiently.

Question content

How to iterate slices of bytes and assign them to fields of a structure?

type s struct {
  f1 []byte
  f2 []byte
  f3 []byte
}

func S s {
  x := s{}
  x.f1 = make([]byte, 4)
  x.f1 = make([]byte, 2)
  x.f1 = make([]byte, 2)
  return x
}

func main() {
  data := []byte{83, 117, 110, 83, 0, 1, 0, 65}

  Z := S()
  //pesudo code from here
  i:= 0
  for field in Z {
    field = data[i:len(field)]
    i += len(field)
  }
Copy after login

expect:

  • f1 = [83,117,110,83]
  • f2 = [0,1]
  • f3 = [0,65]

I've done this before in c/c but I don't know how to do it in go. I need a generic allocation function because I will have several different structures, some of which may not exist in the stream.

Ideally I would like to pass the initialized struct and my code will iteratively populate their struct fields.

Workaround

Use the reflection code in the binary/encoding package.

Step 1: Declare the field as an array instead of a slice.

type s struct {
  f1 [4]byte
  f2 [2]byte
  f3 [2]byte
}
Copy after login

Step 2: Use binary.read to decode the data into a structure

var s s
data := []byte{83, 117, 110, 83, 0, 1, 0, 65}
err := binary.read(bytes.newreader(data), binary.littleendian, &s)
if err != nil {
    log.fatal(err)
}
Copy after login

Step 3: Finished!

fmt.Print(s) // prints {[83 117 110 83] [0 1] [0 65]}
Copy after login

https://www.php.cn/link/42ae1544956fbe6e09242e6cd752444c

The above is the detailed content of Copy bytes into struct fields using reflection. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template