比较命名类型和未命名类型时出现编译错误。

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

Compile error when comparing between named type and unamed type

问题

package main

import (
	"fmt"
	"html/template"
)

func main() {
	fmt.Println(template.HTML("test") == "test")

	htmlString := "test"
	fmt.Println(template.HTML("test") == htmlString)
}

template.HTML是Go语言中的一种类型,用于表示HTML内容。在上面的代码中,我们使用template.HTML将字符串"test"转换为HTML类型。

第一个比较表达式template.HTML("test") == "test"返回true,因为template.HTML类型的值与字符串类型的值相等。

然而,第二个比较表达式template.HTML("test") == htmlString会产生错误。错误信息显示类型不匹配,因为template.HTML类型与字符串类型不同。

这是因为在Go语言中,不同类型的值不能直接进行比较。尽管template.HTML类型的值与字符串类型的值在底层表示上可能相同,但它们被视为不同的类型。

如果你想要比较template.HTML类型的值和字符串类型的值,你可以将template.HTML类型的值转换为字符串类型,然后进行比较。例如,你可以使用string()函数将template.HTML类型的值转换为字符串类型:

fmt.Println(string(template.HTML("test")) == htmlString)

这样就可以避免类型不匹配的错误。

英文:
package main

import (
	"fmt"
	"html/template"
)

func main() {
	fmt.Println(template.HTML("test") == "test")

	htmlString := "test"
	fmt.Println(template.HTML("test") == htmlString)
}

http://play.golang.org/p/dON4eLpGN8

document for template.HTML:
http://golang.org/pkg/html/template/#HTML

The first comparison is true. However, the second comparison yield following error :

> invalid operation: "html/template".HTML("test") == htmlString
> (mismatched types "html/template".HTML and string)

Can someone explain what happened under the hood ?

答案1

得分: 5

简而言之,第二个表达式是无效的,因为它们的类型不兼容。

在Go语言中,每个操作的参数必须是相同的类型。第二个表达式

template.HTML("test") == htmlString

是无效的,因为它比较的是template.HTMLstring类型。虽然template.HTML是从string类型派生出来的,但它们是不兼容的。你应该像这样将变量转换为template.HTML类型:template.HTML(htmlString)

但是第一个表达式

template.HTML("test") == "test"

是有效的,因为常量"test"的类型被解释为template.HTML类型。无类型常量具有默认类型,但它可以根据编译时的上下文推断出任何派生类型。这篇文章详细解释了常量的相关知识。也许这篇文章能够解答你的问题。

英文:

In short, second expression is invalid their types are incompatible.

Every operations in Go, arguments are must be same type. The second expression

template.HTML("test") == htmlString

is invalid since it's comparing template.HTML and string. Although template.HTML is driven from string, but it is incompatible. You should cast the variable like template.HTML(htmlString).

But the first expression

template.HTML("test") == "test"

is valid because the type of constant "test" interpreted as template.HTML. Untyped constant has default type, but it can be any driven type by context at compile time. This article explains about constant in detail. Maybe this article make your question clear.

huangapple
  • 本文由 发表于 2015年3月1日 16:33:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/28791568.html
匿名

发表评论

匿名网友

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

确定