英文:
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.SomeData0
和MyType.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论