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