【发布时间】:2017-10-03 05:51:16
【问题描述】:
作为 Go 的初学者,我无法理解 io.Writer。
我的目标:获取一个结构并将其写入一个 json 文件。
方法:
- 使用 encoding/json.Marshal 将我的结构转换为字节
- 将这些字节提供给os.File Writer
这就是我的工作方式:
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)
}
看了this article之后,我把我的程序改成了这样:
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)
}
在我看来,第一个例子对于初学者来说更直接和更容易理解......但我觉得第二个例子是实现目标的 Go 惯用方式。
问题:
1. 上述假设是否正确(第二个选项是 Go 惯用的)?
2.以上选项有区别吗?哪个选项更好?
3. 实现相同目标的其他方法?
谢谢,
WM
【问题讨论】: