作为Go的初学者,我有理解的问题io.Writer.
我的目标:获取一个结构并将其写入json文件.
方法:
- 用于encoding/json.Marshal将我的结构转换为字节
- 将这些字节提供给os.FileWriter
这就是我的工作方式:
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)
}
Run Code Online (Sandbox Code Playgroud)
阅读本文后,我将程序更改为:
package main
import (
"io" …Run Code Online (Sandbox Code Playgroud)