Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import #7

Closed
ddkwork opened this issue May 18, 2024 · 0 comments
Closed

import #7

ddkwork opened this issue May 18, 2024 · 0 comments

Comments

@ddkwork
Copy link
Owner

ddkwork commented May 18, 2024

package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
	"os"
)

func main() {
	src := `
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
`

	fset := token.NewFileSet()
	node, err := parser.ParseFile(fset, "", src, parser.ParseComments)
	if err != nil {
		fmt.Println(err)
		return
	}

	newImport := &ast.GenDecl{
		Tok: token.IMPORT,
		Specs: []ast.Spec{
			&ast.ImportSpec{
				Path: &ast.BasicLit{
					Kind:  token.STRING,
					Value: `"time"`,
				},
			},
		},
	}

	node.Decls = append([]ast.Decl{newImport}, node.Decls...)

	printer.Fprint(os.Stdout, fset, node)
}
@ddkwork ddkwork closed this as completed May 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant