猿问

如何将字段作为参数传递

我想将字段作为参数传递以从函数返回值


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返回值8问题是如何像参数一样传递它


https://play.golang.org/p/JisnrTxF2EY


慕盖茨4494581
浏览 154回答 1
1回答

慕斯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
随时随地看视频慕课网APP

相关分类

Go
我要回答