Skip to content

Latest commit

 

History

History
173 lines (139 loc) · 2.48 KB

README.md

File metadata and controls

173 lines (139 loc) · 2.48 KB

gg

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

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

安装

go install github.com/shenghui0779/yiigo/cmd/gg@latest

使用

# CLI
gg xxx.go

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

例子

demo.go

package demo

import (
	"context"
	"time"

	"github.com/shenghui0779/yiigo"
)

//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      yiigo.Step
	FieldGenT      T
	FieldGenE      E
}

demo_getter.go

package demo

// Code generated by gg; DO NOT EDIT.

import (
	"context"
	"github.com/shenghui0779/yiigo"
	"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() yiigo.Step {
	if d != nil {
		return d.FieldStep
	}
	return yiigo.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
}