Golang encoding/binary.Size() function examples

package encoding/binary

Size returns how many bytes Write would generate to encode the value v (1st parameter), which must be a fixed-size value or a slice of fixed-size values, or a pointer to such data.

Golang encoding/binary.Size() function usage examples

Example 1 :

 package main

 import (
 "encoding/binary"
 "fmt"
 )

 func main() {
 var a int
 b := [6]int64{1}

 fmt.Println(binary.Size(a)) 
 fmt.Println(binary.Size(b)) 
 }

Output :

-1

64

Example 2 :

 func binaryRead(r io.Reader, order binary.ByteOrder, data interface{}) (n int64, err error) {
 var read int
 buf := make([]byte, binary.Size(data))  // <--- binary.Size()
 if read, err = io.ReadFull(r, buf); err != nil {
 return int64(read), err
 }
 return int64(read), binary.Read(bytes.NewBuffer(buf), order, data)
 }

References :

http://golang.org/pkg/encoding/binary/#Size

https://github.com/conformal/btcwallet/blob/master/keystore/keystore.go

Advertisement