2 回答

TA貢獻1725條經(jīng)驗 獲得超8個贊
您可以在之前將整個復制personB到personA并備份該Age字段:
func updateFields(personA *Person, personB Person) {
tempAge := personA.Age
*personA = personB
personA.Age = tempAge
}

TA貢獻1788條經(jīng)驗 獲得超4個贊
為了簡單地復制每個字段,您可以簡單地執(zhí)行類似*personA = personB. 如果您只需要“不復制”一個特定字段(每次都是相同的字段),您可能只需將該字段的值保存在一個單獨的變量中,使用 復制所有內(nèi)容*personA = personB,然后將值復制回來。但這僅對非常特定的情況有用。例如,它不允許有一組不復制的動態(tài)字段。
如果你想更靈活地做到這一點,你可以使用反射來做到這一點,下面的示例代碼。
請注意,可能存在一些限制。值得注意的是,您只能設置導出的字段。此外,如果您不測試這些限制并且不小心嘗試設置一個不可設置的字段,或者使用不可分配給該字段的類型值等,reflect包將很高興panic. .Set(...)因此,在實際使用該字段之前添加大量檢查是明智的。
import (
"fmt"
"reflect"
)
type Person struct {
FirstName string
LastName int
Age int
HairColor string
EyeColor string
Height string
}
func updateFields(personA *Person, personB Person) {
// .Elem() called to dereference the pointer
aVal := reflect.ValueOf(personA).Elem()
aTyp := aVal.Type()
// no .Elem() called here because it's not a pointer
bVal := reflect.ValueOf(personB)
for i := 0; i < aVal.NumField(); i++ {
// skip the "Age" field:
if aTyp.Field(i).Name == "Age" {
continue
}
// you might want to add some checks here,
// eg stuff like .CanSet(), to avoid panics
aVal.Field(i).Set(bVal.Field(i))
}
}
func main() {
b := Person{
FirstName: "Bruno",
LastName: 1,
Age: 2,
HairColor: "hello",
EyeColor: "world",
Height: "tall",
}
a := Person{}
fmt.Println(a)
updateFields(&a, b)
fmt.Println(a)
}
- 2 回答
- 0 關注
- 146 瀏覽
添加回答
舉報