Io.Writer in Go - Beginner Trying to Understand Them

As a newbie to Go, I have trouble understanding io.Writer.

My goal: take a structure and write it to a json file.

Approach:
- use encoding/json.Marshalto convert my structure to bytes
- pass these bytes to os.FileWriter

Here's how I got started:

package main

import (
    "os"
    "encoding/json"
)

type Person struct {
    Name string
    Age uint
    Occupation []string
}

func MakeBytes(p Person) []byte {
    b, _ := json.Marshal(p)
    return b
}

func main() {
    gandalf := Person{
        "Gandalf",
        56,
        []string{"sourcerer", "foo fighter"},
    }

    myFile, err := os.Create("output1.json")
    if err != nil {
        panic(err)
    }
    myBytes := MakeBytes(gandalf)
    myFile.Write(myBytes)
}

After reading this article , I changed my program to the following:

package main

import (
    "io"
    "os"
    "encoding/json"
)

type Person struct {
    Name string
    Age uint
    Occupation []string
}

// Correct name for this function would be simply Write
// but I use WriteToFile for my understanding
func (p *Person) WriteToFile(w io.Writer) {
    b, _ := json.Marshal(*p)
    w.Write(b)
}

func main() {
    gandalf := Person{
        "Gandalf",
        56,
        []string{"sourcerer", "foo fighter"},
    }

    myFile, err := os.Create("output2.json")
    if err != nil {
        panic(err)
    }
    gandalf.WriteToFile(myFile)
}

In my opinion, the first example is simpler and more understandable for a beginner ... but I have the feeling that the second example is the idiomatic Go way to achieve the goal.

:
1. ( Go )?
2. ? ?
3. ?

,

WM

+6
1

, Writer, , Write - , http.ResponseWriter, , stdout os.Stdout, struct.

io . , , , Reader Writer.

Go more, , Reader Writer , , :)

, ():

// writes json representation of Person to Writer
func (p *Person) WriteJson(w io.Writer) error {
    b, err := json.Marshal(*p)
    if err != nil {
        return err
    }
    _, err = w.Write(b)
    if err != nil {
        return err
    }
    return err
}

, http Response, Stdout ; .

- , ; Person :

  • json
  • json Writer
  • , /

, , Writer, , . > - , , . , , Write(), .

, , ( ReadWriters - , Error() (ei. )).

+6

Source: https://habr.com/ru/post/1017005/


All Articles