0

I want to write a function that takes different struct-types as 1 parameter. Also, I have to be sure, that in these structs is an Id field. So I want a function like this:

MyFunction(object *struct{ Id int })

I tried it with passing the struct as a *struct{ Id int } and an interface{} parameter.

For example, I have these 2 struct-types:

type TableOne struct {
    Id   int
    name string
    date string
}

type TableTwo struct {
    Id      int
    address string
    athome  bool
}

To save them in the database (using reflection) I have the following function:

func SaveMyTables(tablename string, obj *struct{ Id int }) {
    // ... Some code here

    if obj.Id != 0 {
        // ... Some code here
    }

    // ... Some code here
}

I call the function like this:

obj := &TableTwo{
    Id: 5
    address: "some address"
    athome: false
}

myPackage.Save("addresses", obj).

But I get this error:

cannot use obj (type *mytables.TableTwo) as type *struct { Id int } in argument to myPackage.Save

6
  • Go is a strictly-typed language. If you specify a struct type for an argument, that is the type that must be passed, exactly. Commented May 23, 2019 at 17:26
  • @Adrian, i understand. So there is no other way than to implenent the exact same function multiple times, only with an other agrument type? That's exactly what I wanted to prevent. Commented May 23, 2019 at 17:30
  • 1
    You said you tried passing the value in an interface{}. That is the correct method, what didn't work? Commented May 23, 2019 at 17:32
  • @JimB i have to be sure that the struct has a Id int variable, because @ if obj.Id != 0 { Golang requires to know that the variable is there. Also interface{ Id int } does not work. Commented May 23, 2019 at 17:37
  • 2
    You can't. There is no way to have a contract on fields. An interface offers a contract on behavior (as it should). The design needs to be corrected from the ground up. Commented May 23, 2019 at 17:39

1 Answer 1

5

I want to write a function that takes different struct-types as 1 parameter. Also, I have to get sure, that in these struct is an Id field.

As of the current version of Go, you cannot do this. The only way Go supports passing multiple argument types to a single parameter is through the use of interfaces, and interfaces can only specify method sets, not fields.

(Go 2 plans to add generics, and this may be possible then. However, there's no concrete timeline for when that will be available.)

Sign up to request clarification or add additional context in comments.

1 Comment

go generics are now available, but I still don't know how to do this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.