encoder_example_test.go 810 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package rlp
  2. import (
  3. "fmt"
  4. "io"
  5. )
  6. type MyCoolType struct {
  7. Name string
  8. a, b uint
  9. }
  10. // EncodeRLP writes x as RLP list [a, b] that omits the Name field.
  11. func (x *MyCoolType) EncodeRLP(w io.Writer) (err error) {
  12. // Note: the receiver can be a nil pointer. This allows you to
  13. // control the encoding of nil, but it also means that you have to
  14. // check for a nil receiver.
  15. if x == nil {
  16. err = Encode(w, []uint{0, 0})
  17. } else {
  18. err = Encode(w, []uint{x.a, x.b})
  19. }
  20. return err
  21. }
  22. func ExampleEncoder() {
  23. var t *MyCoolType // t is nil pointer to MyCoolType
  24. bytes, _ := EncodeToBytes(t)
  25. fmt.Printf("%v → %X\n", t, bytes)
  26. t = &MyCoolType{Name: "foobar", a: 5, b: 6}
  27. bytes, _ = EncodeToBytes(t)
  28. fmt.Printf("%v → %X\n", t, bytes)
  29. // Output:
  30. // <nil> → C28080
  31. // &{foobar 5 6} → C20506
  32. }