Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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") ?

like image 555
DaveUK Avatar asked Aug 26 '17 03:08

DaveUK


People also ask

How do I convert type in Golang?

Type conversion happens when we assign the value of one data type to another. Statically typed languages like C/C++, Java, provide the support for Implicit Type Conversion but Golang is different, as it doesn't support the Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible.

Does Go support type conversion?

Golang Implicit Type CastingGolang does not support implicit type conversion because of its robust type system. Some languages allow or even require compilers to provide coercion.

Does Golang have a prefix?

In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix.


1 Answers

Convert the value to a string:

func SomeFunction() string {         return string(Foobar) } 
like image 131
Bayta Darell Avatar answered Oct 05 '22 17:10

Bayta Darell