作爲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