Home > Net >  Infer struct structure
Infer struct structure

Time:10-02

I am using this to create a struct without defining a separate type:

data := struct {
    Product *domain.UserProduct
    Options *[]domain.UserProductOption
}{
    Product: userProduct,
    Options: userProductOptions,
}

Is there a way to do the same without defining struct's structure, as number of fields and their types can inferred? Something like:

data := {
    Product: userProduct,
    Options: userProductOptions,
}

CodePudding user response:

As of Go 1.17 there's nothing like that to infer the type of a struct.

There's been some discussion of this in the proposal #35304, but it's still open. To summarize the discussion:

  • foo({x: y}) - unreadable
  • data := _{x: y} - unreadable (?)
  • data := struct {x: y} - overloads the syntax of struct
  • data := tuple {x: y} - new keyword
  • . . .

You're welcome to participate in the discussion and/or submit your own proposal.

I would think something like data := struct _ {X: x, Y: y} should be the most in line with the philosophy of _ being used to omit things (as in this case we want to omit the struct definition).

CodePudding user response:

Is there a way to do the same without defining struct's structure

No. The language doesn't allow it: in Composite literals, it is defined how these work:

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements. Each element may optionally be preceded by a corresponding key.

CompositeLit  = LiteralType LiteralValue .

LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
                SliceType | MapType | TypeName .

LiteralValue  = "{" [ ElementList [ "," ] ] "}" .

The place where you can have the literal value is in an element list:

// the struct type may be defined or literal

// defined type
type User struct {
   Name string
}

// `{"John"}` is the literal value
foo := []User{{"John"}}

// literal type
// `{"John","[email protected]"}` is the literal value
bar := []struct{Name string; Email string}{{"John","[email protected]"}}

  •  Tags:  
  • go
  • Related