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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

GfG
n: 4

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.