#Is there a way to do an or in a type alias?

14 messages · Page 1 of 1 (latest)

viscid linden
#

I know in TypeScript you can do type Foo = number | string, where Foo can either be a number or a string. Is there a way to do that in Go? Thank you for any help.

amber lion
# viscid linden I know in TypeScript you can do `type Foo = number | string`, where Foo can eith...

No, Go doesn't have union types like Typescript. You can use interfaces though, to achieve something similar.

type Foo interface {
  isFoo()
}

type FooString string

func (FooString) isFoo() {}

type FooInt int

func (FooInt) isFoo() {}

Then, when you want to determine the type of a Foo

var foo Foo // pretend this isn't nil
switch foo := foo.(type) {
case FooString:
  // The shadowed `foo` variable is now type FooString
case FooInt:
  // The shadowed `foo` variable is now type FooInt
}
#

You can also use generic type unions, but this isn't exactly the same. It won't allow an instance of Foo to hold either a number or string at runtime. It'd be the same type for the entire runtime of the program, as it's compiled in

type Foo interface {
  int | string
}

func DoSomethingWithFoo[T Foo](f T) {
  // Depending on how this function is invoked, T will either be `int` or `string`
}
viscid linden
#

Thank you.

bright stratus
#

well you can also have a generic function with multiple types

#

ah that's covered in 2nd part of phil's reply

viscid linden
#

I know this is seperate. Is there a way to take an interface type struct, take its values and transform it into another struct, where the field names that match get the value from the interface type and the rest become default values?

i.e:

foo := {
  amount: 2, 
  name: "Foo"
}
type GenericFoo struct {
  amount int
  name string
  description string
  bar float64
}
newFoo := foo.combine(GenericFoo)
fmt.Println("%+v", newFoo)
terminal:
{
  amount 2, 
  name: "Foo",
  description: "",
  bar: 0.0
}
bright stratus
#

interfaces in go are about methods not fields

#

you can use reflection (or even in some case... unsafe) to transfer from one struct to another struct but... it's not very good to do if performance matters

viscid linden
#

thanks

amber lion
bright stratus
#

it's a bit more readable for short stuff yeah (but I was replying before reading the whole thing, my bad)

amber lion
#

All good, I think it added something anyway 👌