Open In App

io.WriteString() Function in Golang with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

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:




// Golang program to illustrate the usage of
// io.WriteString() function
  
// Including main package
package main
  
// Importing fmt, io, and os
import (
    "fmt"
    "io"
    "os"
)
  
// Calling main
func main() {
  
    // Defining w using Stdout
    w := os.Stdout
  
    // Calling WriteString method with its parameters
    n, err := io.WriteString(w, "GfG\n")
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    fmt.Printf("n: %d\n", n)
}


Output:

GfG
n: 4

Example 2:




// Golang program to illustrate the usage of
// io.WriteString() function
  
// Including main package
package main
  
// Importing fmt, io, and os
import (
    "fmt"
    "io"
    "os"
)
  
// Calling main
func main() {
  
    // Defining w using Stdout
    w := os.Stdout
  
    // Calling WriteString method with its parameters
    n, err := io.WriteString(w, "GeeksforGeeks\nis\na\nCS-Portal.\n")
  
    // If error is not nil then panics
    if err != nil {
        panic(err)
    }
  
    // Prints output
    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
Previous
Next
Share your thoughts in the comments
Similar Reads