如何将一个定义为字符串的类型与一个字符串进行比较?

huangapple go评论84阅读模式
英文:

How to compare a type defined as a string with a string

问题

我正在使用具有自定义类型的字符串常量的代码。但是当我有一个输入字符串时,我想要查看这个字符串是否与其中一个常量匹配。但是我得到了一个编译错误,说类型不兼容。我已经使用下面的代码重新创建了这个问题。有没有一种简单的方法来进行这个检查?

我得到的错误是invalid operation: compareVal == NamedFoo (mismatched types string and MyFoo)

这个错误对我来说没有意义,因为MyFoo被定义为一个字符串。我还尝试将我的常量转换为字符串,但是得到了更多的错误,例如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")
    }
}
英文:

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

答案1

得分: 3

当你进行类型定义时,实际上是创建了一个新的类型,在Go语言中无法直接比较不同类型的值。如果这些类型是兼容的,你可以进行转换来比较可比较的值。在这种情况下,你可以将你的MyFoo实例转换为string,或者将string转换为MyFoo实例。

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

英文:

When you do a type definition you are effectively creating a new type and in go it is not possible to compare different types directly. If the types are compatible, you can do a conversion to compare comparable values. In this case, you can either convert your MyFoo instance to string or the string to a MyFoo instance

Also, it seems like you are confusing type assertions and conversions. Conversions allow to convert between compatible types. Check this amazing article for more information on conversion rules in go. A type assertion allows you to get to the concrete value of an interface

huangapple
  • 本文由 发表于 2021年3月19日 14:03:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/66703239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定