首页 > 解决方案 > How to compare a type defined as a string with a string

问题描述

I'm working with code that has string constants with a custom type. But when I have an input string, I want to see if this string matches one of the constants. But I'm getting a compilation error that the types are compatible. I've recreated the problem with the code below. Is there a simple way to make this check?

The error I'm getting with this is invalid operation: compareVal == NamedFoo (mismatched types string and MyFoo)

The error doesn't make sense to me since MyFoo is defined as a string. I also get more errors trying to cast my constant to a string as in NamedFoo.(string)

package main

import "fmt"

type MyFoo string

const (
    NamedFoo MyFoo = "foobar"
)

func main() {
    compareVal := "foobar"

    if compareVal == NamedFoo {
        fmt.Println("Works")
    } else {
        fmt.Println("Didn't Work")
    }
}

标签: go

解决方案


当您进行类型定义时,您实际上是在创建一个新类型,并且在 go 中无法直接比较不同的类型。如果类型兼容,您可以进行转换以比较可比较的值。在这种情况下,您可以将您的MyFoo实例转换string为实例stringMyFoo

此外,您似乎在混淆类型断言和转换。转换允许在兼容类型之间进行转换。查看这篇精彩的文章,了解有关 go 转换规则的更多信息。类型断言允许您获取接口的具体值


推荐阅读