我正在嘗試在 Go 中進(jìn)行一些元編程,并且正在嘗試使用該go/ast包。這是創(chuàng)建 AST 的代碼段:// Create an ASTfooFn := &ast.FuncDecl{ Name: &ast.Ident{Name: "foofn"}, Body: &ast.BlockStmt{ List: []ast.Stmt{&ast.ExprStmt{ X: &ast.CallExpr{ Fun: &ast.Ident{Name: "println"}, Args: []ast.Expr{ &ast.BasicLit{Kind: token.INT, Value: "42"}, }, }, }}, },}f := &ast.File{ Name: &ast.Ident{Name: "foopackage"}, Decls: []ast.Decl{fooFn}, Scope: &ast.Scope{ Objects: map[string]*ast.Object{ "Foo": &ast.Object{ Kind: ast.Fun, Name: "Foo", Decl: fooFn, }, }, },}在這里查看完整的代碼http://play.golang.org/p/zTJdnqVx__應(yīng)該會產(chǎn)生這個(gè)輸出:panic: runtime error: invalid memory address or nil pointer dereference[signal 0xb code=0xffffffff addr=0x0 pc=0x773ae]goroutine 16 [running]:runtime.panic(0x18b5a0, 0x24c8af) /tmp/sandbox/go/src/pkg/runtime/panic.c:279 +0x120go/ast.(*FuncType).Pos(0x0, 0x1c827eb4, 0xfefd02b8, 0x10422360) /tmp/sandbox/go/src/pkg/go/ast/ast.go:446 +0x2ego/ast.(*FuncDecl).Pos(0x10422360, 0x10422360, 0x47, 0xfeee1cb0) /tmp/sandbox/go/src/pkg/go/ast/ast.go:933 +0x40go/printer.(*printer).declList(0x10402840, 0x1040e108, 0x1, 0x1) /tmp/sandbox/go/src/pkg/go/printer/nodes.go:1587 +0x180go/printer.(*printer).file(0x10402840, 0x10442080) /tmp/sandbox/go/src/pkg/go/printer/nodes.go:1597 +0x1e0go/printer.(*printer).printNode(0x10402840, 0x184ba0, 0x10442080, 0x104223c0, 0x0, 0x0) /tmp/sandbox/go/src/pkg/go/printer/printer.go:1087 +0xa40go/printer.(*Config).fprint(0xfeee1e90, 0xfefd02d8, 0x10426180, 0x104181b0, 0x184ba0, 0x10442080, 0x104223c0, 0xfefd02d8, 0x0, 0x0) /tmp/sandbox/go/src/pkg/go/printer/printer.go:1226 +0xc0go/printer.(*Config).Fprint(0xfeee1e90, 0xfefd02d8, 0x10426180, 0x104181b0, 0x184ba0, 0x10442080, 0x0, 0x0)編輯:這是FuncDelc.Type設(shè)置和Scope刪除的工作版本(因?yàn)槲抑辉谠创a緩沖區(qū)之后):http://play.golang.org/p/B0Xp61rSce
1 回答

夢里花落0921
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
看起來您可能需要ast.FuncType
為您的ast.FuncDecl
. 錯(cuò)誤似乎是調(diào)用的結(jié)果IsValid()
對Func
你的(零)的財(cái)產(chǎn)FuncType
。
- 1 回答
- 0 關(guān)注
- 384 瀏覽
添加回答
舉報(bào)
0/150
提交
取消