Skip to content

Option to implement GoStringer instead of Stringer, to allow using the %x verb #282

@jonathangjertsen

Description

@jonathangjertsen

Problem

Go makes an IMO bizarre decision when using the %x verb on an integer Stringer: golang/go#21535

Consider the following (Go playground link: https://go.dev/play/p/6SXwSSmZAHW)

package main

import "fmt"

type HasNone uint16

type HasStringer uint16

func (v HasStringer) String() string { return "String" }

type HasGoStringer uint16

func (v HasGoStringer) GoString() string { return "GoString" }

type HasBoth uint16

func (v HasBoth) String() string   { return "String" }
func (v HasBoth) GoString() string { return "GoString" }

func main() {
	hasNone := HasNone(0x1234)
	hasStringer := HasStringer(0x1234)
	hasGoStringer := HasGoStringer(0x1234)
	hasBoth := HasBoth(0x1234)

	fmt.Printf("None        %%v: %v\t %%#v: %#v\t %%#x: %#x\t\t%%s: %s\n", hasNone, hasNone, hasNone, hasNone)
	fmt.Printf("Stringer    %%v: %v\t %%#v: %#v\t %%#x: %#x\t%%s: %s\n", hasStringer, hasStringer, hasStringer, hasStringer)
	fmt.Printf("GoStringer  %%v: %v\t %%#v: %#v\t %%#x: %#x\t\t%%s: %s\n", hasGoStringer, hasGoStringer, hasGoStringer, hasGoStringer)
	fmt.Printf("Both        %%v: %v\t %%#v: %#v\t %%#x: %#x\t%%s: %s\n", hasBoth, hasBoth, hasBoth, hasBoth)
}

output:

None        %v: 4660	 %#v: 0x1234	 %#x: 0x1234		%s: %!s(main.HasNone=4660)
Stringer    %v: String	 %#v: 0x1234	 %#x: 0x537472696e67	%s: String
GoStringer  %v: 4660	 %#v: GoString	 %#x: 0x1234		%s: %!s(main.HasGoStringer=4660)
Both        %v: String	 %#v: GoString	 %#x: 0x537472696e67	%s: String

None of these are great, but at least GoStringer allows you to select between printing the name (%#v) or the hex value (%x) without doing any type conversions. So it would be nice to be able to generate GoStringer instead of Stringer. It's conceivable that someone might want to generate none or both of the methods, so I guess you should write --gostring --no-string if you want only GoString.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions