1 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以添加第二個(gè)參數(shù)來指示您想要哪個(gè)字段,例如:
func c2(s s, field int) int {
var t int
switch field {
case 0:
t = s.a
case 1:
t = s.b
}
return t
}
或者更方便的方法是傳遞字段的名稱,并使用反射來獲取該字段:
func c3(s s, fieldName string) int {
var t int
t = int(reflect.ValueOf(s).FieldByName(fieldName).Int())
return t
}
或者您可以傳遞字段的地址,并分配指向的值:
func c4(f *int) int {
var t int
t = *f
return t
}
測(cè)試上述解決方案:
x := s{5, 8}
fmt.Println("c2 with a:", c2(x, 0))
fmt.Println("c2 with b:", c2(x, 1))
fmt.Println("c3 with a:", c3(x, "a"))
fmt.Println("c3 with b:", c3(x, "b"))
fmt.Println("c4 with a:", c4(&x.a))
fmt.Println("c4 with b:", c4(&x.b))
哪個(gè)會(huì)輸出(在Go Playground上試試):
c2 with a: 5
c2 with b: 8
c3 with a: 5
c3 with b: 8
c4 with a: 5
c4 with b: 8
- 1 回答
- 0 關(guān)注
- 150 瀏覽
添加回答
舉報(bào)