Skip to content

text/template: make and/or operators short-circuit evaluation #31103

@bep

Description

@bep

Note that the documentation is correct regarding this, so I'm not claiming this is a bug/regression etc. But I suspect the original restriction was motivated by "simpler to implement" -- and since this has become increasingly painful for me lately, I'm testing the water with this issue.

There are at least 3 good arguments in favor of my case:

  1. To avoid nil-pointer situations.
  2. To avoid expensive data initialization when not needed.
  3. The behavior would match the most common boolean AND and OR operators in Go. The current situation is very surprising to most people.
package main

import (
	"io/ioutil"
	"log"
	"text/template"
)

type I interface {
	B() bool
}

type T struct {
}

func (t *T) B() bool {
	return true
}

func main() {
	var t I
	templ, _ := template.New("").Parse("{{ if and .Foo .Foo.B }}TRUE{{ end }}")
	if err := templ.Execute(ioutil.Discard, map[string]interface{}{"Foo": t}); err != nil {
		log.Fatal(err)
	}

}

https://play.golang.org/p/gGdMuJ3-3er

Prints:

2019/03/28 08:45:28 template: :1:19: executing "" at <.Foo.B>: nil pointer evaluating interface {}.B

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions