如何编写一个Go函数来接受不同的结构体?

huangapple go评论73阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年9月1日 08:55:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/32322013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定