使用反射设置字段

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

Set fields using Reflection

问题

我正在努力解决几天来的一些 Go 语言代码问题。我有一个 Go 函数,它会在结构体内设置所有常见字段,比如 createdBy、updatedBy 等等。我已经进行了很多谷歌搜索,并得到了以下代码:

package main

import (
	"fmt"
	"reflect"
	"time"
	"strings"
)
type User struct {
    UserId	       string         `json:"userId"`
    ObjectType         string         `json:"objectType"`
    CreationDate       string         `json:"creationDate"`
    UpdationDate       string         `json:"updationDate"`
    Version            int            `json:"version"`         
}
func main() {
	//fmt.Println("Hello, playground")
	var user = User{}
	var k = setCommonParam(&user)
	var p = k.(*User)
	fmt.Println(p.CreationDate)
	var l = *p
	fmt.Println(l.ObjectType)
	fmt.Println(reflect.TypeOf(k))
	fmt.Println(reflect.TypeOf(user))
	
}

func setCommonParam(obj interface{}) interface{} {
	entityValue := reflect.ValueOf(obj).Elem()
	entityType := entityValue.Type()

	for i:=0; i<entityValue.NumField(); i++ {
		typeField := entityType.Field(i)
		vField := entityValue.Field(i)

		if typeField.Name == "ObjectType" {
			vField.SetString(strings.ToLower(reflect.TypeOf(obj).Elem().Name()))
		} else if typeField.Name == "CreationDate" {	
			vField.SetString(time.Now().Format(time.RFC3339))	
		} else if typeField.Name == "UpdationDate" {
			vField.SetString(time.Now().Format(time.RFC3339))
		} else if typeField.Name == "CreatedBy" {
			
		} else if typeField.Name == "UpdatedBy" {
			
		} else if typeField.Name == "Version" {
			
		}
	}
	return obj
}

有没有办法将以下代码写成一行?

var k = setCommonParam(&user)
var p = k.(*User)
var l = *p

并像这样做:

user = setCommonParam(user)

对不起,我对此还不熟悉。谢谢。

英文:

I am struggling with some Go lang code for a few days. I have a golang function that would set all the common fields like createdBy, updatedBy, etc inside a struct. I have googled a lot and have come up with the following code.

package main
import (
&quot;fmt&quot;
&quot;reflect&quot;
&quot;time&quot;
&quot;strings&quot;
)
type User struct {
UserId	       string         `json:&quot;userId&quot;`
ObjectType         string         `json:&quot;objectType&quot;`
CreationDate       string         `json:&quot;creationDate&quot;`
UpdationDate       string         `json:&quot;updationDate&quot;`
Version            int            `json:&quot;version&quot;`         
}
func main() {
//fmt.Println(&quot;Hello, playground&quot;)
var user = User{}
var k = setCommonParam(&amp;user )
var p = k.(*User)
fmt.Println(p.CreationDate)
var l = *p
fmt.Println(l.ObjectType)
fmt.Println(reflect.TypeOf(k))
fmt.Println(reflect.TypeOf(user))
}
func setCommonParam(obj interface{}) (interface{}) {
entityValue := reflect.ValueOf(obj).Elem()
entityType := entityValue.Type()
for i:=0; i&lt;entityValue.NumField(); i++ {
typeField := entityType.Field(i)
vField := entityValue.Field(i)
if typeField.Name == &quot;ObjectType&quot; {
vField.SetString(strings.ToLower(reflect.TypeOf(obj).Elem().Name()))
} else if typeField.Name == &quot;CreationDate&quot; {	
vField.SetString(time.Now().Format(time.RFC3339))	
} else if typeField.Name == &quot;UpdationDate&quot; {
vField.SetString(time.Now().Format(time.RFC3339))
} else if typeField.Name == &quot;CreatedBy&quot; {
} else if typeField.Name == &quot;UpdatedBy&quot; {
} else if typeField.Name == &quot;Version&quot; {
}
}
return obj
}

Is there any way I can write the following in a single line?

var k = setCommonParam(&amp;user )
var p = k.(*User)
var l = *p

and do something like this:

user = setCommonParam(user)

I am sorry but I am new to this. Thanks.

答案1

得分: 0

如果你的问题是“如何将这3行代码合并为一行?”,那么答案是:

var l = *(setCommonParam(&user).(*User))

英文:

If your question is "how to condense these 3 lines into one?", then the answer is:

var l = *(setCommonParam(&amp;user).(*User))

huangapple
  • 本文由 发表于 2017年9月15日 16:37:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/46235212.html
匿名

发表评论

匿名网友

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

确定