-2

How to create a struct with generic struct inside and init it in go , I see similar question here Generic Structs with Go but the fields is primitive type , I need the field of struct is generic and set this field as other struct

I try but it not work

type ResponseData[T struct{}] struct {
    status          int
    error           string
    soaErrorCode    string
    soaErrorDesc    string
    clientMessageId string
    path            string
    data            T
}

And I try to init it

    message := struct {
        accountId string
    }{
        accountId: "0344561299",
    }
    bodyin := RoutinQueryInput[struct{}]{
        Destination: "AAA-BBB",
        Version:     "1.2",
        Message:     message,
    }

It said :

Cannot use 'message' (type struct {...}) as the type struct{}

In Java, we can create object generic inside a object , how to do that in go?

3
  • struct{} is not a type Commented Dec 8, 2022 at 5:02
  • @Inian struct{} is a type; it's just not a very useful one. It carries no data. Commented Dec 8, 2022 at 5:05
  • 2
    @HymnsForDisco It's quite useful actually :), just not as a type parameter. Commented Dec 8, 2022 at 5:09

1 Answer 1

4

If your type parameter list says [T struct{}], that means type T can only be struct{}. That doesn't mean that it can be any struct type, it literally means struct{} (the empty struct).

There's no type constraint that means "all types which are structs". Even if there was, it wouldn't do you any good, because it doesn't describe any common behaviour.

You should change it to be type ResponseData[T any] so that the data field can be of any type.

It will also be more convenient if you declare your message type as a named type, so you can reference it on instantiation. For example:

    type messageType struct {
        accountId string
    }
    message := messageType{
        accountId: "0344561299",
    }
    bodyin := RoutinQueryInput[messageType]{
        Destination: "AAA-BBB",
        Version:     "1.2",
        Message:     message,
    }
Sign up to request clarification or add additional context in comments.

2 Comments

problem is I want "Message" as a generic type, we cannot define structure of "messageType" from start
@vuhoanghiep1993 then define the field data as any, instead of using generics. Anyway if you follow the advice in this post, you can instantiate RoutinQueryInput with whatever you want, at point of use.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.