0
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 Answer 1

5

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.