gg

command
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2025 License: MIT Imports: 16 Imported by: 0

README

gg

protoc-gen-go 启发,为结构体生成 Get 方法【支持泛型!!!】,避免空指针引起的Panic

Generate Get method for structure (support generics !!!), inspired by protoc-gen-go, avoid Panic caused by nil pointer

安装

go install github.com/noble-gase/og/cmd/gg@latest

使用

# CLI
gg .      # current dir
gg a/b/c  # specify dir
gg xxx.go # specify file

# go generate
//go:generate gg xxx.go

例子

demo.go
package demo

import (
	"context"
	"time"

	"github.com/noble-gase/ne"
)

//go:generate gg demo.go

type Code int

type Demo[T any, E comparable] struct {
	FieldInt       int
	FieldFloat     float64
	FieldBool      bool
	FieldStr       string
	FieldArr       []int
	FieldMap       map[string]int
	FieldAny       any
	FieldInterface interface{}
	FieldCode      Code
	FieldCtx       context.Context
	FieldTime      time.Time
	FieldStep      ne.Step
	FieldGenT      T
	FieldGenE      E
}
demo_getter.go
package demo

// Code generated by gg; DO NOT EDIT.

import (
	"context"
	"github.com/shenghui0779/og"
	"time"
)

// Get methods for Demo [T, E]

func (d *Demo[T, E]) GetFieldInt() int {
	if d != nil {
		return d.FieldInt
	}
	return 0
}

func (d *Demo[T, E]) GetFieldFloat() float64 {
	if d != nil {
		return d.FieldFloat
	}
	return 0
}

func (d *Demo[T, E]) GetFieldBool() bool {
	if d != nil {
		return d.FieldBool
	}
	return false
}

func (d *Demo[T, E]) GetFieldStr() string {
	if d != nil {
		return d.FieldStr
	}
	return ""
}

func (d *Demo[T, E]) GetFieldArr() []int {
	if d != nil {
		return d.FieldArr
	}
	return nil
}

func (d *Demo[T, E]) GetFieldMap() map[string]int {
	if d != nil {
		return d.FieldMap
	}
	return nil
}

func (d *Demo[T, E]) GetFieldAny() any {
	if d != nil {
		return d.FieldAny
	}
	return nil
}

func (d *Demo[T, E]) GetFieldInterface() interface{} {
	if d != nil {
		return d.FieldInterface
	}
	return nil
}

func (d *Demo[T, E]) GetFieldCode() Code {
	if d != nil {
		return d.FieldCode
	}
	return 0
}

func (d *Demo[T, E]) GetFieldCtx() context.Context {
	if d != nil {
		return d.FieldCtx
	}
	return nil
}

func (d *Demo[T, E]) GetFieldTime() time.Time {
	if d != nil {
		return d.FieldTime
	}
	return time.Time{}
}

func (d *Demo[T, E]) GetFieldStep() og.Step {
	if d != nil {
		return d.FieldStep
	}
	return og.Step{}
}

func (d *Demo[T, E]) GetFieldGenT() T {
	if d != nil {
		return d.FieldGenT
	}
	var v T
	return v
}

func (d *Demo[T, E]) GetFieldGenE() E {
	if d != nil {
		return d.FieldGenE
	}
	var v E
	return v
}

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

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