我是 golang 新手,所以我认为我使用 go-ini 库读取配置文件并将其映射到嵌入式结构时做错了什么。我在谷歌中没有找到任何有效的示例,所以我很高兴在这里获得一些帮助。
如果我在“mapTo”调用中使用类型“EmbeddedTestData”作为参数,则我的测试程序可以工作,但如果我使用包含嵌入类型的“TestData”类型,则变量“data”最后为空。
/*
config.ini contains following example data:
[clientServer]
Port = ":1111"
WsPath = "/ws"
[courtServer]
port = ":2222"
wsPath = "/cs"
*/
package main
import (
"fmt"
"github.com/go-ini/ini"
"os"
)
type TestData struct {
EmbeddedTestData
}
type EmbeddedTestData struct {
Port string
WsPath string
}
func main() {
// load ini-file
inidata, err := ini.Load("config.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
// data := new(EmbeddedTestData) -> this works fine!
data := new(TestData) // doesn't work -> Content in variable 'data': &{{ }}
err = inidata.Section("clientServer").MapTo(data)
fmt.Println("Content in variable 'data': ", data)
}
如果我使用类型“TestData”,我希望变量“data”最终包含配置文件中相应部分的 Port/WsPath 的映射数据。
我也是一个新的 Golang 学习者 但我找到了你的代码的修复方法 您的代码中的第一个问题是
type TestData struct {
EmbeddedTestData
}
要定义您应该使用的结构
type <name> struct {
// field1 type
// field2 type
// field3 type
// ...
}
但你没有给你的类型命名
所以让我们更改它并给它一个名称,以便我们可以访问 TestData 结构中的 EmbeddedTestData 结构
我们给它起一个像 d 这样的名字,所以我们有
type TestData struct {
d EmbeddedTestData
}
现在如果我们改变线路
err = inidata.Section("clientServer").MapTo(data)
到
err = inidata.Section("clientServer").MapTo(data.d)
指向 TestData 结构中的 EmbeddedTestData 结构并再次运行代码,我们得到相同的输出
但是当我们打印错误时
err=inidata.Section("clientServer").MapTo(data.d)
我们得到
不是指向结构的指针
如果我们在代码中添加 & 来指向 EmbeddedTestData 结构 它应该有效
所以最终的代码看起来像这样
/*
config.ini contains following example data:
[clientServer]
Port = ":1111"
WsPath = "/ws"
[courtServer]
port = ":2222"
wsPath = "/cs"
*/
package main
import (
"fmt"
"os"
"github.com/go-ini/ini"
)
type TestData struct {
d EmbeddedTestData
}
type EmbeddedTestData struct {
Port string
WsPath string
}
func main() {
// load ini-file
inidata, err := ini.Load("config.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
data := new(TestData)
err = inidata.Section("clientServer").MapTo(&data.d)
fmt.Println("Content in variable 'data': ", data)
}