What is Go lang func NewEncoder(w io.Writer) *Encoder?

func NewEncoder(w io.Writer) *Encoder is a function defined in the encoding/json package which gets a JSON encoding of any type and encodes/writes it any writable stream that implements a io.Writer interface. The Encoder object can then be used to perform methods such as Encode(), SetEscapeHTML(), Error(), Unwrap().

Parameters

w: Writable stream that implements the io.Writer interface.

Return Value

*Encoder: Object of the type Encoder defined in the encoding/json package.

Example

package main
import (
"encoding/json"
"os"
"log"
)
func main() {
type Student struct {
Name, Major string
RollNumber int32
}
stu := new(Student)
stu.Name = "Hassan"
stu.Major = "Physics"
stu.RollNumber = 18100026
enc := json.NewEncoder(os.Stdout)
err := enc.Encode(&stu)
log.Println(err)
}

Explanation

In the above example, we define a struct Student with properties Name, Major, and RollNumber and created an object stu of type Student. We pass standard output stream os.Stdout to the func NewEncoder(w io.Writer) *Encoder method which returns an Encoder object stored in enc. We use the Encode() method accessible to enc which serializes the stu object into JSON and writes the JSON objects to the standard output stream. The Encode method returns an error instance which reports whether any error took place in the encoding process.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved