decode_tail_test.go 930 B

123456789101112131415161718192021222324252627282930313233
  1. package rlp
  2. import (
  3. "bytes"
  4. "fmt"
  5. )
  6. type structWithTail struct {
  7. A, B uint
  8. C []uint `rlp:"tail"`
  9. }
  10. func ExampleDecode_structTagTail() {
  11. // In this example, the "tail" struct tag is used to decode lists of
  12. // differing length into a struct.
  13. var val structWithTail
  14. err := Decode(bytes.NewReader([]byte{0xC4, 0x01, 0x02, 0x03, 0x04}), &val)
  15. fmt.Printf("with 4 elements: err=%v val=%v\n", err, val)
  16. err = Decode(bytes.NewReader([]byte{0xC6, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), &val)
  17. fmt.Printf("with 6 elements: err=%v val=%v\n", err, val)
  18. // Note that at least two list elements must be present to
  19. // fill fields A and B:
  20. err = Decode(bytes.NewReader([]byte{0xC1, 0x01}), &val)
  21. fmt.Printf("with 1 element: err=%q\n", err)
  22. // Output:
  23. // with 4 elements: err=<nil> val={1 2 [3 4]}
  24. // with 6 elements: err=<nil> val={1 2 [3 4 5 6]}
  25. // with 1 element: err="rlp: too few elements for rlp.structWithTail"
  26. }