Unmarshal table/section #976
Answered
by
bogdan-the-great
bogdan-the-great
asked this question in
Questions
-
Hi, I don't understand how can I unmarshal values from a table. [values]
value1 = 2
value2 = "two"
value3 = 0.2 This snippet only unmarshals my file when it doesn't have a table (values) in itpackage main
import (
"fmt"
"log"
"os"
"github.com/pelletier/go-toml/v2"
)
type Config struct {
Value1 int
Value2 string
Value3 float64
}
func main() {
var cfg Config
data, err := os.ReadFile("test.toml")
if err != nil {
log.Fatal(err)
}
err = toml.Unmarshal(data, &cfg)
if err != nil {
panic(err)
}
fmt.Println(cfg.Value1)
fmt.Println(cfg.Value2)
fmt.Println(cfg.Value3)
} I know that I'm doing something wrong with the struct declaration but don't know what. I have searched for similar issues, but i don't really understand them e.g. #960. |
Beta Was this translation helpful? Give feedback.
Answered by
bogdan-the-great
Dec 3, 2024
Replies: 1 comment
-
Okay I figured it out. You need to wrap it all in another struct, as follows: package main
import (
"fmt"
"log"
"os"
"github.com/pelletier/go-toml/v2"
)
type Config struct {
Values Values "values"
}
type Values struct {
Value1 int
Value2 string
Value3 float64
}
func main() {
var cfg Config
data, err := os.ReadFile("test.toml")
if err != nil {
log.Fatal(err)
}
err = toml.Unmarshal(data, &cfg)
if err != nil {
panic(err)
}
fmt.Println(cfg.Values.Value1)
fmt.Println(cfg.Values.Value2)
fmt.Println(cfg.Values.Value3)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
bogdan-the-great
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Okay I figured it out. You need to wrap it all in another struct, as follows: