io.WriteString() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The WriteString() function in Go language is used to write the contents of the stated string “s” to the writer “w”, which takes a slice of bytes. And if “w” is implemented by StringWriter then its WriteString method is called immediately. Else, w.Write is invoked strictly once. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func WriteString(w Writer, s string) (n int, err error)
Here, “w” is the writer, and “s” is the string that is written to the writer.
Return value: It returns the total number of bytes of the content of type int and also returns an error if any.
Below examples illustrates the use of above method:
Example 1:
package main
import (
"fmt"
"io"
"os"
)
func main() {
w := os.Stdout
n, err := io.WriteString(w, "GfG\n" )
if err != nil {
panic(err)
}
fmt.Printf( "n: %d\n" , n)
}
|
Output:
GfG
n: 4
Example 2:
package main
import (
"fmt"
"io"
"os"
)
func main() {
w := os.Stdout
n, err := io.WriteString(w, "GeeksforGeeks\nis\na\nCS-Portal.\n" )
if err != nil {
panic(err)
}
fmt.Printf( "n: %d\n" , n)
}
|
Output:
GeeksforGeeks
is
a
CS-Portal.
n: 30
Here, in the above example, “Stdout” is used in order to create a default file descriptor where the stated content is written.
Last Updated :
05 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...