我有自动生成的代码。简化版:

package main

// begin of A
func main(){
    ParseReader("x")
}
func parseInclude(fileName string) (interface{}, error) {
    got, _ := ParseReader(fileName)
    return got, nil
}
// end of A
type grammar struct {
    pos   int
    run  func(*parser) (interface{}, error)
}
var g = &grammar{
    pos:  1,
    run: (*parser).callonIncludeOp1,
}

type parser struct {
    filename string
    cur      current
}
func (p *parser) callonIncludeOp1() (interface{}, error) {
    return p.cur.onIncludeOp1("x")
}
func (p *parser) parse(g *grammar) (val interface{}, err error) {
    return g.pos, nil
}

type current struct {
    pos  int
}
// B
func (c *current) onIncludeOp1(qfilename interface{}) (interface{}, error) {
    got, _ := parseInclude("x")
    return got, nil
}

func ParseReader(filename string) (interface{}, error) {
    p := &parser{ filename: filename }
    return p.parse(g)
}

编译后出现错误
./prog.go:19: initialization loop:
    /home/gCDfp4/prog.go:19 g refers to
    /home/gCDfp4/prog.go:25 (*parser).callonIncludeOp1 refers to
    /home/gCDfp4/prog.go:36 (*current).onIncludeOp1 refers to
    /home/gCDfp4/prog.go:7 parseInclude refers to
    /home/gCDfp4/prog.go:41 ParseReader refers to
    /home/gCDfp4/prog.go:19 g

我需要在语法上进行递归调用,因为我有用于解析其他文件的预处理程序运算符“#include”。

因为它是自动生成的代码,所以我只能在块A或函数B中修改代码。

如何中断初始化周期?

最佳答案

这是package initialization的结果,其中:

您的example in a playground返回一些更直接的信息:

tmp/sandbox395359317/main.go:21: initialization loop:
    prog.go:21 g refers to
    prog.go:28 (*parser).callonIncludeOp1 refers to
    prog.go:21 g
techniques in Go for loose coupling,例如接口(interface)
作为一个例子(不是最优的,但至少破坏了初始化周期),您可以在//A中添加:

type parseIncluder interface {
    parseInclude(fileName string) (interface{}, error)
}

func (c *current) parseInclude(fileName string) (interface{}, error) {
    return parseInclude(fileName)
}
//B中,对parseInclude()的调用变为:
got, _ := c.cParseIncluder().parseInclude("x")
看到Go plaground并单击Run:没有更多的initialization loop

OP Red Skotinapackage init() function使用了不同的方法:
var gProxy grammar

func init() { gProxy = g }
func parseInclude(fileName string) (interface{}, error) {
    got, _ := ParseReaderProxy(fileName)
    return got, nil
}
func ParseReaderProxy(filename string) (interface{}, error) {
    p := &parser{filename: filename}
    return p.parse(gProxy)
}

10-06 13:16