Converting a custom type to string in Go

In this bizarre example, someone has created a new type which is really just a string:

type CustomType string

const (
        Foobar CustomType = "somestring"
)

func SomeFunction() string {
        return Foobar
}

However, this code fails to compile:

cannot use Foobar (type CustomType) as type string in return argument

How would you fix SomeFunction so that it is able to return the string value of Foobar ("somestring") ?


Solution 1:

Convert the value to a string:

func SomeFunction() string {
        return string(Foobar)
}

Solution 2:

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

Solution 3:

For every type T, there is a corresponding conversion operation T(x) that converts the value x to type T. A conversion from one type to another is allowed if both have the same underlying type, or if both are unnamed pointer types that point to variables of the same underlying type; these conversions change the type but not the representation of the value. If x is assignable to T, a conversion is permitted but is usually redundant. - Taken from The Go Programming Language - by Alan A. A. Donovan

As per your example here are some of the different examples which will return the value.

package main

import "fmt"

type CustomType string

const (
    Foobar CustomType = "somestring"
)

func SomeFunction() CustomType {
    return Foobar
}
func SomeOtherFunction() string {
    return string(Foobar)
}
func SomeOtherFunction2() CustomType {
    return CustomType("somestring") // Here value is a static string.
}
func main() {
    fmt.Println(SomeFunction())
    fmt.Println(SomeOtherFunction())
    fmt.Println(SomeOtherFunction2())
}

It will output:

somestring
somestring
somestring

The Go Playground link