Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
json

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

Abdul Monum

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

golang
json

CONTRIBUTOR

Abdul Monum
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring