Yes, you can do this. Say you have an *ast.Block b that's populated
with statements and you want to insert a statement at index i.
// first put together the statement "a = 42"
identA := ast.NewIdent("a")
fortyTwo := &ast.BasicLit{Kind: token.INT, Value: "42"}
assignment := &ast.AssignStmt{Lhs: []ast.Expr{identA}, Rhs:
[]ast.Expr{fortyTwo}}
// allocate a new statement list big enough for our new statement
list := make([]ast.Stmt, len(b.List) + 1)
copy(list, b.List[:i])
list[i] = assignment
copy(list[i+1:], b.List[i:])
b.List = list
(In some cases you could use append instead of explicitly allocating a
new list if you know you're adding to the end of the block.)
- Evan
(In some cases you could use append instead of explicitly allocating a
new list if you know you're adding to the end of the block.)
That's a neat trick, but I think my way is clearer even though it's more code.
- Evan
var list []ast.Stmt // or = make([]ast.Stmt, 0, len(b.List)+1) if you care
list = append(list, b.List[:i]...)
list = append(list, assignment)
list = append(list, b.List[i:]...)
b.List = list
Russ