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") ?
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.
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.
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.
Convert the value to a string:
func SomeFunction() string { return string(Foobar) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With