如何标记无法修改的嵌入结构体的字段?

huangapple go评论85阅读模式
英文:

How do you tag fields of embedded structs which you cannot modify?

问题

假设有一个外部库libA,它声明了NotMyType

type NotMyType struct {
  NotMyField string
}

你想将它嵌入到自己的类型中,而你使用了一个ORM(对象关系映射),该ORM使用标签来调整列属性。

type MyType struct {
  SomeData0 string  `orm:"nullable"`
  SomeData1 string  `orm:"nullable"`
  libA.NotMyType
}

例如,列MyType.SomeData0MyType.SomeData1是可为空的。

是否可以在不修改NotMyType的情况下,给NotMyField添加orm:"nullable"标签?

英文:

Suppose there is an external library libA who declares NotMyType.

type NotMyType struct {
  NotMyField string
}

And you would like to embed it with one of your own types, which you use with an ORM, which uses the tags to adjust column properties.

type MyType struct {
  SomeData0 string  `orm:"nullable"`
  SomeData1 string  `orm:"nullable"`
  libA.NotMyType
}

For example, columns MyType.SomeData0 and MyType.SomeData1 are NULLABLE.

Is it possible to tag NotMyField with orm:"nullable" without modifying NotMyType?

答案1

得分: 1

好的,以下是翻译好的内容:

编辑:回答错误,我的错

好的,我想我明白了。我以前从未使用过 reflect,所以可能是错的。但是:

看一下我刚刚做的:

> https://play.golang.org/p/U0uyomL-It

我有一个结构体

type User struct {
    name string
    age  int
}

没有标签。

我使用以下代码获取字段:

field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
if !ok {
    panic("Field not found")
}

然后我使用以下代码设置一个新的标签:

//setStructTag(&field)

func setStructTag(f *reflect.StructField) {
    f.Tag = "`json:name-field`"
}

希望我的研究能对你有所帮助 如何标记无法修改的嵌入结构体的字段?

英文:

EDIT: wrong answer, my bad

Okep i think i got it. I have never used reflect before so maybe i'm wrong. But :

Take a look at what I just do :

> https://play.golang.org/p/U0uyomL-It

I have a struct

type User struct {
    name string
    age  int
}

With no tag.

I get the field with

field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
if !ok {
	panic("Field not found")
}

And i set a new tag with

//setStructTag(&field)

func setStructTag(f *reflect.StructField) {
	f.Tag = "`json:name-field`"
}

Hope my researche will help you 如何标记无法修改的嵌入结构体的字段?

答案2

得分: 0

Go是自省的。
它具有自省功能(例如,find-class允许查看现有的类),但没有干预功能(例如,ensure-class在运行时创建/修改类)。

所以你不能。

英文:

Go is introspective.
It has introspection (e.g. find-class allows to look at existing classes) but no intercession (e.g. ensure-class creates/modifies a class at runtime).

So you can't.

huangapple
  • 本文由 发表于 2016年11月22日 17:37:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/40738292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定