Converting a custom type to string in Go
Convert the value to a string:
func SomeFunction() string {
return string(Foobar)
}
Better to define a String
function for the Customtype
- it can make your life easier over time - you have better control over things as and if the structure evolves. If you really need SomeFunction
then let it return Foobar.String()
package main
import (
"fmt"
)
type CustomType string
const (
Foobar CustomType = "somestring"
)
func main() {
fmt.Println("Hello, playground", Foobar)
fmt.Printf("%s", Foobar)
fmt.Println("\n\n")
fmt.Println(SomeFunction())
}
func (c CustomType) String() string {
fmt.Println("Executing String() for CustomType!")
return string(c)
}
func SomeFunction() string {
return Foobar.String()
}
https://play.golang.org/p/jMKMcQjQj3