私は構造体の個々のフィールドをループして、各フィールドに関数を適用し、元の構造体全体を変更されたフィールド値で返します。 明らかに、これは1つの構造体の場合は難しいことではありませんが、私はその関数を動的にする必要があります。このインスタンスの は、Golang:構造体のフィールドをループして構造体を返します。
type Post struct{
fieldName data `check:"value1"
...
}
type Post struct{
fieldName data `check:"value2"
...
}
以下のように私はポストとカテゴリ構造体を参照しています私は、構造体のそれぞれのフィールドをループしcheck
が持っているどのような値に応じてスイッチ機能を持って、関数を適用しますそのフィールドのdata
が
type Datastore interface {
...
}
func CheckSwitch(value reflect.Value){
//this loops through the fields
for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
tag := value.Type().Field(i).Tag // returns the tag string
field := value.Field(i) // returns the content of the struct type field
switch tag.Get("check"){
case "value1":
fmt.Println(field.String())//or some other function
case "value2":
fmt.Println(field.String())//or some other function
....
}
///how could I modify the struct data during the switch seen above and then return the struct with the updated values?
}
}
//the check function is used i.e
function foo(){
p:=Post{fieldName:"bar"}
check(p)
}
func check(d Datastore){
value := reflect.ValueOf(d) ///this gets the fields contained inside the struct
CheckSwitch(value)
...
}
を次のようにどのように私は、本質的には、上記の例ではインターフェイスで指定された構造体に戻しCheckSwitch
でswitch文の後に変更された値を再挿入します。 他に必要がある場合はお知らせください。 ありがとう
ちょっとお返事ありがとう!フィールド値を設定したら、 'reflect.Value'を返す必要がありますか?この場合、後で使用するために、これを指定した構造体、つまり 'Post'にどのように再挿入するのですか? –
更新された回答を参照してください。 –