If I want to know whether a variable is of type string, I can do a type assertion:
S, OK:= value.(string)
If value is of type string, then OKis true, and S is the original value.
But this type assertion doesn't work for custom string types; for example:
type MyString string
For a variable of this type, the above type assertion returns false for OK.
How can I determine if a variable is of type string, or of an equivalent type, without a separate assertion for each such equivalent type?
You cannot perform a type assertion or a type switch to a string, as the exact type does not match. The closest you can get is to use the reflect package and check the value's Kind:
var S string
ref := reflect.ValueOf(value)
if ref.Kind() == reflect.String {
S = ref.String()
}
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