#Is there a way to do an or in a type alias?
14 messages · Page 1 of 1 (latest)
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`
}
Thank you.
well you can also have a generic function with multiple types
func Foo[T int | string](x T) {
for instance https://go.dev/play/p/9BGTlLWcq8E
ah that's covered in 2nd part of phil's reply
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
}
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
thanks
Ah, I always forget you can omit the interface entirely 😅
it's a bit more readable for short stuff yeah (but I was replying before reading the whole thing, my bad)
All good, I think it added something anyway 👌