Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

decode tables with values of custom type #170

Closed
ecc1 opened this issue Apr 11, 2017 · 4 comments
Closed

decode tables with values of custom type #170

ecc1 opened this issue Apr 11, 2017 · 4 comments
Labels

Comments

@ecc1
Copy link

ecc1 commented Apr 11, 2017

I expected to be able to decode a table into a map from string to a type of my choosing, as long as I provided an unmarshaling function for that type (like the duration example). But it doesn't seem to work.

Here's a program that I expect to panic during decoding:

package main

import (
	"fmt"

	"github.com/BurntSushi/toml"
)

type config struct {
	Sites map[string]custom
}

type custom struct {
	Value string
}

func main() {
	var conf config
	blob := `
	    [sites]

	    ebay   = "https://ebay.com"
	    google = "https://google.com"
	`
	toml.Decode(blob, &conf)
	fmt.Printf("% v\n", conf)
}

func (c *custom) UnmarshalText(text []byte) error {
	panic("unmarshal")
}

But the UnmarshalText function is never called, and the result is just {map[]}

Am I doing something wrong, or is this not possible?

@BurntSushi
Copy link
Owner

Looks like this might be a bug? If you use map[string]*custom instead of map[string]custom, then it works.

@cespare
Copy link
Collaborator

cespare commented Apr 11, 2017

Yeah, it should work even though map values are not addressable.

@cespare cespare added the bug label Apr 11, 2017
@ecc1
Copy link
Author

ecc1 commented Apr 11, 2017

I tried with the *custom value, but then the UnmarshalText function gets called with a nil pointer as the receiver (so replacing the panic with something "useful" doesn't actually work). This version panics:

package main

import (
	"fmt"

	"github.com/BurntSushi/toml"
)

type config struct {
	Sites map[string]*custom
}

type custom struct {
	Value string
}

func main() {
	var conf config
	blob := `
	    [sites]

	    ebay   = "https://ebay.com"
	    google = "https://google.com"
	`
	toml.Decode(blob, &conf)
	fmt.Printf("% v\n", conf)
}

func (c *custom) UnmarshalText(text []byte) error {
	c.Value = string(text)
	return nil
}

@arp242
Copy link
Collaborator

arp242 commented May 27, 2022

Verified this is fixed now, for both examples.

@arp242 arp242 closed this as completed May 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants