Allowing for encoding of values that implement compatible interfaces#1
Allowing for encoding of values that implement compatible interfaces#1mariusor wants to merge 9 commits intodyninc:masterfrom
Conversation
…nterface Currently: fmt.Stringer and encoding.TextMarshaller
|
Hi, I don't know if this repository is still maintained, but if it is, I made a small improvement to it and I would appreciate if someone can review it. |
…tion too Also refactored the logic into a separate function
|
I realized I haven't provided a use case where this would be needed. In my case I have a type which is an alias for a byte slice. However the slice is pretty long, 65 characters, of which only the first 7-8 are needed, basically a SHA hash. So for me it would be useful if the value of such a type would be restricted to just 8 characters, which is already being done for when marshaling it for Json with the help of a type Hash []byte
func (h Hash) MarshalText () ([]byte, error) {
return []byte(h[0:8])
}
var hash = Hash("42ea17b556f4f77c8d9fcdfde313e7847f2115f0cc1a2ae04347a568960396ae")
hashes := make(map[string][]Hash)
hashes["hashes"] = []Hash{ hash, }
s, _ := qstring.MarshalString(&hashes)
fmt.Println(s)
// prints hashes=42ea17b5 |
| return out | ||
| } | ||
|
|
||
| func compatibleInterfaceValue(field reflect.Value) (string, bool) { |
There was a problem hiding this comment.
In the end I think relying on encoding.TextMarshaler and fmt.Stringer interfaces for compatible types is a mistake, as using their methods implicitly might be a problem for structs that have a different logic for them than what qstring would expect.
I think a better idea would be to create a qstring.Marshaler interface which types would be required to implement explicitly.
A concrete example would be a named type for a slice. A qstring specific implementation would have to prepend the property name (or qstring tag) for every value, but a plain Stringer/TextMarshaler method does not have the complete information for it, and as such would return a broken value.
Removed last mention of dyninc organization
When it's type implements a known compatible interface
Currently: fmt.Stringer and encoding.TextMarshaller