如何将字段作为参数传递
How to pass field as parameter
我想将字段作为参数传递给函数return值
package main
import (
"fmt"
)
type s struct {
a int
b int
}
func c(s s) int {
var t int
t = s.a // how to change this to t=s.b just by pass parameter
return t
}
func main() {
fmt.Println(c(s{5, 8}))
}
有时我想 t = s.a
而其他时候我想 t = s.b
到 return 值 8
问题是如何像参数一样传递它[=15] =]
您可以添加第二个参数来表示您想要哪个字段,例如:
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: 5
c2 with b: 8
c3 with a: 5
c3 with b: 8
c4 with a: 5
c4 with b: 8
我想将字段作为参数传递给函数return值
package main
import (
"fmt"
)
type s struct {
a int
b int
}
func c(s s) int {
var t int
t = s.a // how to change this to t=s.b just by pass parameter
return t
}
func main() {
fmt.Println(c(s{5, 8}))
}
有时我想 t = s.a
而其他时候我想 t = s.b
到 return 值 8
问题是如何像参数一样传递它[=15] =]
您可以添加第二个参数来表示您想要哪个字段,例如:
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: 5
c2 with b: 8
c3 with a: 5
c3 with b: 8
c4 with a: 5
c4 with b: 8