Reference loop error

Morning, folks

               So was learning myself a bit of text/template package when I came across this supposedly common error. Did a minor search on Go’s Github issues and here, but to no success. I know the reference cycle exists, but shouldn’t this be already dealt with? Here’s a small chunk of code.

package something

import (

type Entry func() string
var Registry []Entry = []Entry{Summary, A, B}

func Summary() string {
        buf := &bytes.Buffer{}
        str := "{{.}}"
        tlp := template.Must(template.New("Summ").Parse(str))
        tlp.Execute(buf, Registry)
        return buf.String()

func A() string {
        return "a"

func B() string {
        return "b"

Will endup with an error similar to this:

# something
something.go:?:?: initialization loop:
        .../something.go:?:?: Registry refers to
        .../something.go:?:?: Summary refers to
        .../something.go:?:?: Registry

That is interesting. I can reproduce it. The way I was able to get around it was by putting the initialization of Registry into an init function like this:

func init() {
    Registry = []Entry{Summary, A, B}

And then it seems to be OK.

               Thanks for the answer, Sean. Totally forgot about init(). Good to know its a way out, but looking at, I’m not sure its original purpose was to avoid that kind of technical detail. Besides this cryptic line Besides initializations that cannot be expressed as declarations,, init()'s purpose seems to be to initialize stuff in a singleton manner.

I’m not sure about init's intended purpose, but rsc recommended that approach here.

1 Like

Awesome! Thanks for issue link!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.