Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToString() function in Go

Tags:

tostring

go

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
like image 693
deamon Avatar asked Oct 03 '22 23:10

deamon


3 Answers

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
like image 233
zzzz Avatar answered Oct 07 '22 16:10

zzzz


When you have own struct, you could have own convert-to-string function.

package main

import (
    "fmt"
)

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

func (c Color) String() string {
    return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}

func main() {
    c := Color{Red: 123, Green: 11, Blue: 34}
    fmt.Println(c) //[123, 11, 34]
}
like image 27
Rio Avatar answered Oct 07 '22 18:10

Rio


Another example with a struct :

package types

import "fmt"

type MyType struct {
    Id   int    
    Name string
}

func (t MyType) String() string {
    return fmt.Sprintf(
    "[%d : %s]",
    t.Id, 
    t.Name)
}

Be careful when using it,
concatenation with '+' doesn't compile :

t := types.MyType{ 12, "Blabla" }

fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly
like image 6
lgu Avatar answered Oct 07 '22 16:10

lgu