我有幾個配置 JSON 文件,每個文件都有每個文件的特定結構類型目前我為每個文件/結構名稱創建了一個函數:type ConfigOne struct { App string `json:"app"` Web string `json:"web"` Archive string `json:"archive"`}type ConfigTwo struct { Options string `json:"options"` Source string `json:"source"` Backup bool `json:"backup"`} func ReadJsonConfigOne(file string, config *ConfigOne) error { str := GetContentFile(file) return json.Unmarshal([]byte(str), config)}func ReadJsonConfigTwo(file string, config *ConfigTwo) error { str := GetContentFile(file) return json.Unmarshal([]byte(str), config)}func main() { One := ConfigOne{} err := ReadJsonConfigOne("file_one.json", &One) Two := ConfigTwo{} err := ReadJsonConfigTwo("file_two.json", &Two) ../..}如何僅使用一個函數并將結構作為參數傳遞?
1 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
func ReadJsonConfig(file string, config interface{}) error {
str := GetContentFile(file)
return json.Unmarshal([]byte(str), config)
}
用法
func main() {
One := ConfigOne{}
err := ReadJsonConfig("file_one.json", &One)
Two := ConfigTwo{}
err := ReadJsonConfig("file_two.json", &Two)
../..
}
使用接口作為函數參數。
- 1 回答
- 0 關注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消