慕斯709654
您可以添加第二个参数来指示您想要哪个字段,例如: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}测试上述解决方案: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))哪个会输出(在Go Playground上试试):c2 with a: 5c2 with b: 8c3 with a: 5c3 with b: 8c4 with a: 5c4 with b: 8