genstruct

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2025 License: MIT Imports: 6 Imported by: 1

README

genstruct

A Go library for generating statically defined Go structs with support for references between structures.

Features

  • Generate Go code for static structs and arrays
  • Automatic creation of constants, variables, and slices
  • Smart naming of variables based on identifier fields
  • Reference embedding via struct tags to connect related structs
  • Customizable code generation

Installation

go get github.com/conneroisu/genstruct

Basic Usage

// Define your struct type
type Animal struct {
    ID     string
    Name   string
    Species string
    Diet   string
}

// Create a slice of structs
animals := []Animal{
    {ID: "lion-001", Name: "Leo", Species: "Lion", Diet: "Carnivore"},
    {ID: "tiger-001", Name: "Stripes", Species: "Tiger", Diet: "Carnivore"},
}

// Configure the generator
config := genstruct.Config{
    PackageName:   "zoo",          // Target package name
    TypeName:      "Animal",       // Struct type name
    ConstantIdent: "Animal",       // Prefix for constants
    VarPrefix:     "Animal",       // Prefix for variables
    OutputFile:    "animals.go",   // Output file path
}

// Generate the code
generator := genstruct.NewGenerator(config, animals)
err := generator.Generate()

Struct Reference Embedding

A powerful feature of genstruct is the ability to automatically populate fields in one struct by referencing values from another struct.

How it works
  1. Define your structs with reference fields
  2. Use the structgen tag to specify the source field
  3. Pass additional reference datasets to NewGenerator
Example
// Define your tag struct
type Tag struct {
    ID   string
    Name string
    Slug string
}

// Define your post struct with references to tags
type Post struct {
    ID       string
    Title    string
    TagSlugs []string  // Contains tag slugs
    Tags     []Tag     `structgen:"TagSlugs"` // Will be populated from TagSlugs
}

// Create your data
tags := []Tag{
    {ID: "tag-001", Name: "Go", Slug: "go"},
    {ID: "tag-002", Name: "Programming", Slug: "programming"},
}

posts := []Post{
    {
        ID: "post-001", 
        Title: "Introduction to Go",
        TagSlugs: []string{"go", "programming"},
    },
}

// Generate code with both datasets
generator := genstruct.NewGenerator(config, posts, tags)
err := generator.Generate()

The generated code will include Posts with their Tags field populated from the referenced Tags.

Config Options

  • PackageName: The package name for the generated file
  • TypeName: The name of the struct type
  • ConstantIdent: Prefix for generated constants
  • VarPrefix: Prefix for generated variables
  • OutputFile: The output file path
  • IdentifierFields: Fields to use for naming (default: "ID", "Name", "Slug", "Title", "Key", "Code")
  • CustomVarNameFn: Optional function to customize variable naming

Dependencies

Documentation

Overview

Package genstruct provides an importable package for generating static golang struct arrays.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// PackageName defines the Target package name (optional)
	// If not provided, the package name will be the same as the given struct.
	PackageName      string
	TypeName         string   // The name of the struct type to generate
	ConstantIdent    string   // Prefix for constants (e.g., "Post" for "PostMyPostID")
	VarPrefix        string   // Prefix for variables (e.g., "Post" for "PostMyPost")
	OutputFile       string   // Output file name
	IdentifierFields []string // Fields to try using for naming, in priority order (optional)
	// Custom function to generate variable names (optional)
	// If provided, this takes precedence over IdentifierFields
	CustomVarNameFn func(structValue reflect.Value) string
}

Config holds the configuration for code generation of static structs and arrays.

type EmptyError

type EmptyError struct{}

EmptyError is returned when the data given is empty.

func (EmptyError) Error

func (e EmptyError) Error() string

Error returns the error message

type Generator

type Generator struct {
	Config Config
	Data   any            // The primary array of structs to generate code for
	Refs   map[string]any // Additional arrays that can be referenced
	File   *jen.File
}

Generator is responsible for generating code for static struct arrays

func NewGenerator

func NewGenerator(config Config, data any, refs ...any) *Generator

NewGenerator creates a new generator instance with support for struct references

Parameters:

  • config: Configuration options for code generation
  • data: The primary array of structs to generate code for
  • refs: Optional additional arrays that can be referenced by the primary data

The refs parameters enable the use of struct tags with the `structgen` tag to reference data between structs. For example, a Post struct with a TagSlugs field can reference Tag structs using the tag `structgen:"TagSlugs"`.

Example usage:

generator := genstruct.NewGenerator(config, posts, tags)

func (*Generator) Generate

func (g *Generator) Generate() error

Generate performs the code generation

type InvalidTypeError

type InvalidTypeError struct {
	Kind reflect.Kind
}

InvalidTypeError is returned when the type of the data is not a struct.

func (InvalidTypeError) Error

func (e InvalidTypeError) Error() string

Error returns the error message

type NonSliceOrArrayError

type NonSliceOrArrayError struct {
	Kind reflect.Kind
}

NonSliceOrArrayError is returned when the data is not a slice or array.

func (NonSliceOrArrayError) Error

func (e NonSliceOrArrayError) Error() string

Error returns the error message

Directories

Path Synopsis
examples
blog-posts-tags command
zoo command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL