0

I'm new to Golang, My question is how to make function accept generic type of parameter. Here is the specific problem I met recently:

I defined a struct which contains a function

type TestArgs struct {
    name string
    ...
    customAssertForTypeA func(array []*pb.TypeA)
    customAssertForTypeB func(array []*pb.TypeB)
}

// Define the test case with TestArgs.
tests := []TestArgs{
        {
            name: "Test A",
            customAssertForTypeA: func(array []*pb.TypeA) {
                // Some code
            }
        },
        {
            name: "Test B",
            customAssertForTypeB: func(array []*pb.TypeB) {
                // Some code
            }
        },
}

My question is how to make customerAssert function accept generic type of parameter? I saw some similar question with solution interface{}, so I tried

customAssert func(array interface{})

and it doesn't work.

1 Answer 1

3

Type assertions ( https://tour.golang.org/methods/15 ) is what you need when you have an interface{} and want to access to the concrete value:

type TestArgs struct {
    name         string
    customAssert func(interface{})
}

// Define the test case with TestArgs.
tests := []TestArgs{
    {
        name: "Test A",
        customAssert: func(param interface{}) {
            // Some code
            array, ok := param.([]*pb.TypeA)
            if !ok {
                t.Fatal("assertion error TypeA")
            }
            // use array
        },
    },
    {
        name: "Test B",
        customAssert: func(param interface{}) {
            // Some code
            array, ok := param.([]*pb.TypeB)
            if !ok {
                t.Fatal("assertion error TypeB")
            }
            // use array
        },
    },
}
Sign up to request clarification or add additional context in comments.

Comments

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.