The strings package revisited

We first talked about the handy strings package back in Chapter 4, The Uses of Composite Types. This section will address the functions of the strings package that are related to file input and output.

The first part of str.go is shown in the following Go code:

package main 
 
import ( 
    "fmt" 
    "io" 
    "os" 
    "strings" 
) 

The second code segment of str.go is as follows:

func main() { 
 
    r := strings.NewReader("test") 
    fmt.Println("r length:", r.Len()) 

The strings.NewReader() function creates a read-only Reader from a string. The strings.Reader object implements the io.Reader, io.ReaderAt, io.Seeker, io.WriterTo, io.ByteScanner, and io.RuneScanner interfaces.

The third part of str.go follows next:

    b := make([]byte, 1) 
    for { 
        n, err := r.Read(b) 
        if err == io.EOF { 
            break 
        } 
 
        if err != nil { 
            fmt.Println(err) 
            continue 
        } 
        fmt.Printf("Read %s Bytes: %d
", b, n) 
    } 

Here you can see how you to use strings.Reader as an io.Reader interface in order to read a string byte by byte using the Read() function.

The last code portion of str.go contains the following Go code:

    s := strings.NewReader("This is an error!
") 
    fmt.Println("r length:", s.Len()) 
    n, err := s.WriteTo(os.Stderr) 
 
    if err != nil { 
        fmt.Println(err) 
        return 
    } 
    fmt.Printf("Wrote %d bytes to os.Stderr
", n) 
} 

In this code segment, you can see how you can write to standard error with the help of the strings package.

Executing str.go will generate the following output:

$ go run str.go
r length: 4
Read t Bytes: 1
Read e Bytes: 1
Read s Bytes: 1
Read t Bytes: 1
r length: 18
This is an error!
Wrote 18 bytes to os.Stderr
$ go run str.go 2>/dev/null
r length: 4
Read t Bytes: 1
Read e Bytes: 1
Read s Bytes: 1
Read t Bytes: 1
r length: 18
Wrote 18 bytes to os.Stderr
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.214.155