Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a Go/Golang type assertion for "type MyString string"?

Tags:

go

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?

like image 986
Martin Del Vecchio Avatar asked Dec 22 '25 00:12

Martin Del Vecchio


1 Answers

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()
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!