-2

i want to pass field as parameter to return value from function

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}))
}

some times i want to make t = s.a and other time i wanted t = s.b to return value 8 the question is how to pass it like parameter

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

icza
  • 389,944
  • 63
  • 907
  • 827
user17148257
  • 149
  • 2
  • 7
  • 3
    You may add a 2nd parameter to tell which field to use. You may also pass the address of the field, and assign / return the pointed value (the field value). – icza Nov 10 '21 at 16:41
  • @icza You are the same one that help me and answer correct In https://stackoverflow.com/a/69751096/17148257 and the same one I don't understand him. please write it in code because I am Beginner – user17148257 Nov 10 '21 at 16:48

1 Answers1

2

You may add a 2nd parameter to signal which field you want, for example:

func c2(s s, field int) int {
    var t int
    switch field {
    case 0:
        t = s.a
    case 1:
        t = s.b
    }
    return t
}

Or a more convenient way is to pass the name of the field, and use reflection to get that field:

func c3(s s, fieldName string) int {
    var t int
    t = int(reflect.ValueOf(s).FieldByName(fieldName).Int())
    return t
}

Or you may pass the address of the field, and assign the pointed value:

func c4(f *int) int {
    var t int
    t = *f
    return t
}

Testing the above solutions:

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))

Which will output (try it on the 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
icza
  • 389,944
  • 63
  • 907
  • 827
  • Even though I agree with all your suggestions because they answer the question, the OP should probably have asked a different question that avoids this approach in the first place. If a function sometimes needs fieldA and sometimes fieldB the logic for taking that decision should probably be encapsulated in the object itself, and therefore the function should probably be a method of that object. – Bazzz Nov 10 '21 at 17:59
  • @Bazzz I agree, but there are cases when you're just using a struct defined in another package, to which you can't "attach" methods. – icza Nov 10 '21 at 18:03