go - 如何使用 go 代码动态创建结构及其属性?

标签 go

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

例如:

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

type User struct {
    Name string
}

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

你能请别人帮忙找到一个方法吗

最佳答案

使用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.
}

在 Playground 上试试:https://play.golang.org/p/YhPAeos4-ek

关于go - 如何使用 go 代码动态创建结构及其属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49820863/

相关文章:

go - 如何将 int32 unicode 转换为字符串

c - Golang 使用 cgo 从共享 c 库调用函数

go - 使用 go 设置 Web 服务器

go - 如何通过转发到死信主题来限制 Google Pub/Sub 传送尝试?

go - 从文件中读取字节到内存中

list - Golang 中 LinkedList<T> 的等价物是什么

golang 从 stdin 扫描一行数字

image - Go Code 在 go test 和 go run 中的行为不同

logging - 为什么我应该使用 log.Println 而不是 fmt.Println?

go - 找不到命令 'bee'