比如說(shuō)你有這樣的東西,試圖讓這個(gè)例子盡可能簡(jiǎn)單。type Home struct { Bedroom string Bathroom string}您如何將字段名稱(chēng)或您可以傳遞給函數(shù)?func (this *Home) AddRoomName(fieldname, value string) { this.fieldname = value}顯然這是行不通的......我能看到的唯一方法是使用兩個(gè)函數(shù),當(dāng)結(jié)構(gòu)變得非常大并且有很多類(lèi)似的代碼時(shí),這兩個(gè)函數(shù)會(huì)增加很多額外的代碼。func (this *Home) AddBedroomName(value string) { this.Bedroom = value}func (this *Home) AddBathroomName(value string) { this.Bathroom = value}
3 回答

侃侃爾雅
TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
對(duì)接口值使用類(lèi)型斷言:
package main
import "fmt"
type Test struct {
S string
I int
}
func (t *Test) setField(name string, value interface{}) {
switch name {
case "S":
t.S = value.(string)
case "I":
t.I = value.(int)
}
}
func main() {
t := &Test{"Hello", 0}
fmt.Println(t.S, t.I)
t.setField("S", "Goodbye")
t.setField("I", 1)
fmt.Println(t.S, t.I)
}
- 3 回答
- 0 關(guān)注
- 171 瀏覽
添加回答
舉報(bào)
0/150
提交
取消