gpt4 book ai didi

go - 初始化周期错误

转载 作者:IT王子 更新时间:2023-10-29 01:58:36 24 4
gpt4 key购买 nike

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

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”来解析其他文件。

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

我怎样才能打破初始化周期?

最佳答案

这是 package initialization 的结果其中:

Dependency analysis does not rely on the actual values of the variables, only on lexical references to them in the source, analyzed transitively.

For instance, if a variable x's initialization expression refers to a function whose body refers to variable y then x depends on y.

As in: "A reference to a variable or function is an identifier denoting that variable or function."

你的 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然后单击运行:不再有初始化循环


OP Red Skotina使用了不同的方法 package 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)
}

关于go - 初始化周期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com