Datsik
Datsik

Reputation: 14824

How can I convert a custom type to a string?

I'm using a package and instead of returning a string, it returns a economy.ClassId You can see here

I want to pass the economy.ClassId which is just a string of numbers like "531569319" to a function that takes a string not a economy.ClassId so is there a way to convert this type to a string or no. Thanks.

I know you could like strconv.FormatUint() but what would I use for a custom type.

Upvotes: 3

Views: 6407

Answers (4)

Zoltán
Zoltán

Reputation: 22146

Here's an example of converting custom types which have an underlying string type back to string:

type CustomType string

const (
    StereoType CustomType = "stereotype"
    ArcheType CustomType  = "archetype"
)

func printString(word string) {
    println(word)
}

Now if you call printString(StereoType), you'll get a compilation error saying

cannot use StereoType (constant "stereotype" of type CustomType) as type string in argument to printString

The solution is to cast it back to a string like this:

printString(string(StereoType))

Upvotes: 0

ruakh
ruakh

Reputation: 183211

ClassId is declared as type ClassId uint64, so although a ClassId isn't exactly the same as a uint64, they have the same underlying type, and you can therefore convert from one to the other. To convert a value x to type T (when permitted), you write T(x). So, in your case:

 funcThatTakesAString(strconv.FormatUint(uint64(classId), 10))

Upvotes: 5

Adam Vincze
Adam Vincze

Reputation: 871

more generally you could implement the stringer interface on your type https://golang.org/pkg/fmt/#Stringer

func (c ClassId) String() string {
    return strconv.FormatUint(uint64(c),10)
}

and use that otherFunc(classId.String())

http://play.golang.org/p/cgdQZNR8GF

PS: also acronymes (ID) should be all capitals

http://talks.golang.org/2014/names.slide#6

Upvotes: 6

Eddy R.
Eddy R.

Reputation: 1129

Another approach that is perhaps more idiomatic is to use fmt.Sprintf using Go's format string specification.

Two examples...

The following converts the classId into a string base 10 number:

classIDStr := fmt.Sprintf("%d", classId)

The following converts it into a string hexadecimal number, with a-f digits in lower case:

classIDHex := fmt.Sprintf("%x", classId)

Upvotes: 0

Related Questions