【问题标题】:How to create a struct and its attributes dynamically using go code?如何使用 go 代码动态创建结构及其属性?
【发布时间】:2018-04-13 15:50:05
【问题描述】:

我是 golang 的新手 如何从 gocode 动态创建结构和属性, 最后必须将其存储为文件。

例如:

结构名称:user 默认情况下,它必须创建Name 属性

type User struct {
    Name string
}

它必须存储为文件ex: user_struct.go

你能不能请人帮忙找到一种方法来做到这一点

【问题讨论】:

  • 请清楚你真正想要完成的事情。
  • 使用 text/template 编写 Go 代码。使用go/printer 格式化。
  • @Peter 能否请您详细解释一下或举个例子

标签: go


【解决方案1】:

使用text/template 编写 Go 代码。由于我不知道您想如何详细执行此操作,因此我将在示例中使用一个简单的模板。任何一种现实世界的模板都会产生格式错误的代码,但是感谢 go fmt 你几乎只需要正确地换行(如果你遇到问题,可以使用分号)。 go fmt 在后台使用go/printer,你也可以。

有关详细信息,请参阅链接的包文档和示例。

package main

import (
    "bytes"
    "go/parser"
    "go/printer"
    "go/token"
    "html/template"
    "io"
    "log"
    "os"
)

var structTpl = `
    package main

    type {{ . }} struct {
            Name string
    }
    `

func main() {
    // Only do this once per template at the start of your program.
    // Then simply call Execute as necessary.
    tpl := template.Must(template.New("foo").Parse(structTpl))

    messy := &bytes.Buffer{}
    tpl.Execute(messy, "User")

    // Parse the code
    fset := &token.FileSet{}
    ast, err := parser.ParseFile(fset, "", messy, parser.ParseComments|parser.DeclarationErrors)
    if err != nil {
        log.Fatal(err)
    }

    // Print the code, neatly formatted.
    neat := &bytes.Buffer{}
    err = printer.Fprint(neat, fset, ast)
    if err != nil {
        log.Fatal(err)
    }

    io.Copy(os.Stdout, neat) // Or write to file as desired.
}

在操场上尝试一下:https://play.golang.org/p/YhPAeos4-ek

【讨论】:

    【解决方案2】:

    如果您正在寻找有关结构、接收器等的基于 ast 的元信息,您可以考虑以下几点:

    package main
    import  "github.com/viant/toolbox"
    
    func main() {
    
        goCodeLocation := ".."
        fileSetInfo, err := toolbox.NewFileSetInfo(goCodeLocation)
        if err != nil {
            panic(err)
        }
        toolbox.Dump(fileSetInfo)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      相关资源
      最近更新 更多