作为Go的初学者,我在理解io.Writer
时遇到了问题。io.Writer in Go - 试图理解它们的初学者
我的目标:采取一个结构并将其写入一个json文件。
方法:
- 使用encoding/json.Marshal
到我的结构转换为字节
- 喂这些字节到os.File
作家
这是我如何得到它的工作:
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 idiomatic)?
2.上述选项有差异吗?哪个选项更好?
3.其他方式实现相同的目标?
谢谢
WM