Workspace
  • Introduction
  • Algorithm
    • 二叉树
    • 排序算法
  • Basic Knowledge
    • CAP定理
    • CAS-SSO-单点登陆
    • 单向认证-双向认证
  • CICD
  • Cloud Native
  • Docker
    • Docker特性
    • Docker资源隔离
  • Golang
    • Standard Library
      • Archive
        • Builtin
        • Zip
    • Golang-container包
    • Golang-fallthrough关键字
    • Golang For Slect
    • Golang-Goroutine泄露
    • Golang Interface
    • Golang-json.Unmarshal
    • Golang Label
    • Golang Map String Struct
    • Golang Map To Struct
    • Golang Override Package Function
    • Golang-Slice删除元素
    • Golang Switch
    • Golang-sync.Cond
    • Golang-sync.Map
    • Golang-sync.once
    • Golang-type关键字
    • Golang-代码生成
    • golang-并发数控制
    • Golang-并发退出
    • Golang-插件系统
    • Golang-继承
    • Golang之channel
    • Golang之continue
    • Golang之make与new和nil
    • Golang之map
    • Golang之reflect
    • Golang之类型判断
    • Golang代码质量检测
    • Golang变量避坑
    • Golang字符串遍历
    • golang并发控制代码示例
    • Golang性能优化
    • Golang死锁
    • goroutine-协程-线程-进程
    • go值传递
    • go内存逃逸分析
    • go并发MGP模式
    • go并发控制
    • 垃圾回收-三色法
  • Istio
    • 服务网格
  • Jenkins
    • Jenkin On K 8 S
    • Jenkins Mac
  • Kubernetes
    • Deployment
    • k8s容器内查看-cpu-memory分配情况
    • kube-proxy原理
    • Kubernetes Informers
    • Kubernetes扩展点
    • Kubernetes部署策略
    • Pod Non Root
    • Pod驱逐
    • PV PVC Storage Class
    • Security Context
    • 优雅热更新
  • Python
    • Python-vs-Golang协程区别
  • Serviceless
  • Shell
    • Shell小技巧
  • VPN
    • OC Serv
  • Redis
Powered by GitBook
On this page

Was this helpful?

  1. Golang

Golang-代码生成

元编程是一种计算程序可以将代码看待成数据的能力。

如果能够将代码看作数据,那么代码就可以像数据一样在运行时被修改、更新和替换;元编程赋予了编程语言更大的表达能力,能够让我们将一些计算过程从运行时挪到编译时、通过编译期间的展开生成代码或者允许程序在运行时改变自身行为的能力。

总而言之,元编程其实是一种使用代码生成代码的方式,无论是编译期间生成的代码,还是运行时改变代码的行为都是生成代码的一种。

例子

代码main.go 里含有//go:generate stringer -type=Pill

package main

import "fmt"

//go:generate stringer -type=Pill
type Pill int

const (
    Placebo Pill = iota
    Aspirin
    Ibuprofen
    Paracetamol
    Acetaminophen = Paracetamol
)

func main() {
    fmt.Println(Placebo.String(), Acetaminophen.String())
}

生成 代码 go generate 会生成 pill_string.go 如下

// Code generated by "stringer -type=Pill"; DO NOT EDIT.

package main

import "strconv"

func _() {
    // An "invalid array index" compiler error signifies that the constant values have changed.
    // Re-run the stringer command to generate them again.
    var x [1]struct{}
    _ = x[Placebo-0]
    _ = x[Aspirin-1]
    _ = x[Ibuprofen-2]
    _ = x[Paracetamol-3]
}

const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"

var _Pill_index = [...]uint8{0, 7, 14, 23, 34}

func (i Pill) String() string {
    if i < 0 || i >= Pill(len(_Pill_index)-1) {
        return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
    }
    return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
PreviousGolang-type关键字Nextgolang-并发数控制

Last updated 4 years ago

Was this helpful?