HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

ToString() function in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
functiontostringstackoverflow

Problem

The strings.Join function takes slices of strings only:

s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))


But it would be nice to be able to pass arbitrary objects which implement a ToString() function.

type ToStringConverter interface {
    ToString() string
}


Is there something like this in Go or do I have to decorate existing types like int with ToString methods and write a wrapper around strings.Join?

func Join(a []ToStringConverter, sep string) string

Solution

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}


Playground: http://play.golang.org/p/Azql7_pDAA

Output

101010

Code Snippets

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Context

Stack Overflow Q#13247644, score: 277

Revisions (0)

No revisions yet.