go-yaml / yaml

YAML support for the Go language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Marshaling integer values to hexadecimal representation

xtheandrew opened this issue · comments

How can I marshal a number from a structure to YAML in hexadecimal representation?

I have a structure with integer fields, the representation of which makes sense to humans in hexadecimal form. I want to save this data to a YAML file for manual editing and then load it from the file. go-yaml (I use v3) encodes integers in decimal form only.

I tried to make a custom marshaler based on the documentation (playground link):

type Uint32Hex uint32

func (U Uint32Hex) MarshalYAML() (interface{}, error) {
	return fmt.Sprintf("0x%x", U), nil
}

type DeviceInfo struct {
	VendorId Uint32Hex `yaml:"vendorid"`
}

But in this case, the number is generated as a string:

vendorid: "0xdeadbeef"

And in order to then unmarshal this line into a number, I will also have to write a custom unmarshaler.

Is there any other way?

So far, I've made a fork and added the ability to set the format in the form of structure tags:

type DeviceInfo struct {
	VendorId uint32 `yaml:"vendorid,hex"`
}

I replaced the module in go.mod and that solved my problem for now. But it would be nice to have a built-in feature.