gpt4 book ai didi

go - 可以反射(reflect)ast的结构

转载 作者:行者123 更新时间:2023-12-03 10:09:44 27 4
gpt4 key购买 nike

我试图实现某种方法来从* ast.TypeSpec获取reflect.TypeOf(),以使用该结构,而无需将其导入代码中(我将在后面解释)。现在我有这个项目结构:

.
├─ main.go
└─ entities
├─ costumer.go
└─ person.go
文件:
// entities/costumer.go
package entities

import "time"

type Costumer struct {
PersonId int
S *int
CreatedAt time.Time
UpdatedAt *time.Time
Goods []struct {
Name string
GoodsId int
}
Goods2
}

func (*Costumer) TableName() string {
return "CustomName"
}

type Goods2 struct {
Name string
Goods2Id int
}

// entities/person.go
package entities

type Person struct {
Id int
Name string
Age int
}

// main.go
package main

import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"log"
)

// Main aa
func main() {
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
packages, err := parser.ParseDir(fset, "./entities", nil, 0)

if err != nil {
panic(err)
}

for _, pack := range packages {

for _, file := range pack.Files {
// Inspect the AST and print all identifiers and literals.
ast.Inspect(file, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.TypeSpec: // Gets Type assertions
fmt.Println(x.Name.Name)

v := x.Type.(*ast.StructType)
for _, field := range v.Fields.List {

for _, name := range field.Names {

// get field.Type as string
var typeNameBuf bytes.Buffer
err := printer.Fprint(&typeNameBuf, fset, field.Type)
if err != nil {
log.Fatalf("failed printing %s", err)
}
fmt.Printf("field %+v has type %+v\n", name.Name, typeNameBuf.String())
}

}
fmt.Println()

}

return true
})
}
}
}

我需要某种方式来获取 CostumerGoods2Person结构在代码中使用。现在,我要专门调用 Costumer.TableName方法并接收它的结果。
我无法导入该软件包,因为稍后它将是一个CLI,并且仅接收要解析/检查的文件夹( parser.ParseDir(fset, "<folder goes here>", nil, 0))
有什么想法,建议或技巧吗?

最佳答案

Is possible to reflect an struct from ast in Go[...]?


不,您必须重新设计。

关于go - 可以反射(reflect)ast的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64196547/

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