golang strings.NewReader

Why strings.Reader value types can efficiently read the string

Type and strings.Builder contrary, strings.Reader efficient to read the string type exist. The latter is mainly reflected in the efficiency of its string read mechanism that encapsulates a lot of best practices for reading content on a string value.

strings.Reader type of value (hereinafter referred to as Reader value) allows us to easily read the contents of a string. In the read process, Reader byte count value stored in the read (hereinafter referred to as read count).

Read count also represents the start position of the next read the index. Reader value is relying on such a count, and slice expression against a string value, enabling fast read.

In addition, the read count is an important basis when fallback position setting and reading. Although it belongs to the internal structure of the Reader value, but we can and Size it calculated the value of the method by Len

Reader has the most value for reading methods are updated in a timely manner has been read count. For example, ReadByte method will be successful after the read count value plus 1.

As another example, ReadRune method after a successful read, the number of bytes read will be occupied by characters as a count increment.

However, ReadAt method is an exception. It will not be read according to the read count, it will not update it after reading. Because of this, this method is free to read any content Reader its value belongs.

// Example 1. 
    Reader1: = strings.NewReader (
         " . Chinese Returns A of the new new Reader Reading SimpleNewReader from S " +
             " . Similar to bytes.NewBufferString It IS and But More Efficient Read-only " )
 % D \ n- " , reader1.Size () -int64 (reader1.Len ())) 
    FMT .Printf ( " : len% D \ n- " // length of the original string, reader1.Len ()) 141
    by:= make([]byte,20)
    reader1.ReadAt (by, 2 ) // This method is not the original value of the count is the same, or the length len is the original length 

    of buf1: = the make ([] byte , . 3 ) // original value offset length len +3 to -3 
     reader1.Read (of buf1)
     FMT .Printf ( " len:% D value:% S \ n- " , reader1.Len (), String (of buf1))

Print results

len: 141 is
len: value 138: the 

In addition, Seek Reader value method also updates the value of the read count. In fact, this is the main role of the Seek method of setting the starting index position at first reading

offset2 := int64(17)
expectedIndex := reader1.Size() - int64(reader1.Len()) + offset2
fmt.Printf("Seek with offset %d and whence %d ...\n", offset2, io.SeekCurrent)
readingIndex, _ := reader1.Seek(offset2, io.SeekCurrent)
fmt.Printf("The reading index in reader: %d (returned by Seek)\n", readingIndex)
fmt.Printf("The reading index in reader: %d (computed by me)\n", expectedIndex)

 

Guess you like

Origin www.cnblogs.com/jackey2015/p/11774956.html