1
type Human struct {
   Name string
   Age string | int  // <--- this is the problem
}

I want to do something like Node.js and declare a field with a union type.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Michleloso
  • 11
  • 1
  • This is called union types and golang doesn't have it. If you _want_ this flexibility, you'll have to use `any`. – Sergio Tulentsev Jul 08 '22 at 10:34
  • 3
    The most appropriate solution will depend on the context (mainly, how the data type will be used). – Hymns For Disco Jul 08 '22 at 10:36
  • If by `interface{}` you mean the *empty interface* and not interface types in general, then you can declare unions with [General interfaces](https://go.dev/ref/spec#General_interfaces): *"In their most general form, an interface element may also be an arbitrary type term `T`, or a term of the form `~T` specifying the underlying type `T`, **or a union of terms `t1|t2|…|tn`**."* – mkopriva Jul 08 '22 at 10:42

0 Answers0