英文:
How to write a Go function to accept different structs?
问题
我正在编写一个函数,用于解析一个配置JSON文件,并使用json.Unmarshal将其数据存储在一个结构体中。经过一些研究,我已经得到了一个Config结构体和一个Server_Config结构体,作为config中的一个字段,以便我可以根据需要添加不同的配置结构体字段。
如何编写一个parseJSON函数来处理不同类型的结构体?
代码:
Server.go
type Server_Config struct {
    html_templates string
}
type Config struct {
    Server_Config
}
func main() {
    config := Config{}
    ParseJSON("server_config.json", &config)
    fmt.Printf("%T\n", config.html_templates)
    fmt.Printf(config.html_templates)
}
config.go
package main
import(
    "encoding/json"
    "io/ioutil"
    "log"
)
func ParseJSON(file string, config Config) {
    configFile, err := ioutil.ReadFile(file)
    if err != nil {
        log.Fatal(err)
    }
    err = json.Unmarshal(configFile, &config)
    if err != nil {
        log.Fatal(err)
    }
}
或者如果有更好的方法来完成所有这些,请告诉我。我对Go语言还很陌生,我的大脑中刻着Java的约定。
英文:
I am writing a function that parses a config JSON file and using json.Unmarshal stores its data in a struct. I've done some research and it's gotten me the point where I have a Config struct and a Server_Config struct as a field in config to allow me to add more fields as I want different config-like structs.
How can I write one parseJSON function to work for different types of structs?
Code:
Server.go
type Server_Config struct {
	html_templates string
}
type Config struct {
	Server_Config
}
func main() {
	config := Config{}
	ParseJSON("server_config.json", &config)
	fmt.Printf("%T\n", config.html_templates)
	fmt.Printf(config.html_templates)
}
config.go
package main
import(
	"encoding/json"
	"io/ioutil"
	"log"
)
func ParseJSON(file string, config Config) {
	configFile, err := ioutil.ReadFile(file)
	if err != nil {
		log.Fatal(err)
	}
	err = json.Unmarshal(configFile, &config)
	if err != nil {
		log.Fatal(err)
	}
}
Or if there is a better way to do all this let me know that as well. Pretty new to Go and I have Java conventions carved into my brain.
答案1
得分: 6
使用interface{}:
func ParseJSON(file string, val interface{}) {
    configFile, err := ioutil.ReadFile(file)
    if err != nil {
        log.Fatal(err)
    }
    err = json.Unmarshal(configFile, val)
    if err != nil {
        log.Fatal(err)
    }
}
调用该函数的方式是相同的。
英文:
Use interface{}:
func ParseJSON(file string, val interface{}) {
    configFile, err := ioutil.ReadFile(file)
    if err != nil {
        log.Fatal(err)
    }
    err = json.Unmarshal(configFile, val)
    if err != nil {
        log.Fatal(err)
    }
}
Calling the function is the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论