英文:
How do I do a Go/Golang type assertion for "type MyString string"?
问题
如果我想知道一个变量是否是字符串类型,我可以进行类型断言:
S, OK := value.(string)
如果value是字符串类型,那么OK为true,S就是原始值。
但是这种类型断言对于自定义的字符串类型是不起作用的;例如:
type MyString string
对于这种类型的变量,上述类型断言会使OK为false。
如何确定一个变量是字符串类型,或者是等效类型的,而不需要为每个等效类型进行单独的断言呢?
英文:
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?
答案1
得分: 5
你不能对字符串执行类型断言或类型切换,因为确切的类型不匹配。你能做的最接近的方法是使用reflect
包并检查值的Kind
:
var S string
ref := reflect.ValueOf(value)
if ref.Kind() == reflect.String {
S = ref.String()
}
英文:
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()
}
答案2
得分: 0
为什么要使用断言?它是用于接口的。尝试像这样进行转换:
type MyString string
var s MyString = "test"
var t string
t = string(s)
英文:
Why you use an assertion, it's for interfaces. Try conversion like:
type MyString string
var s MyString = "test"
var t string
t = string(s)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论