I'm wondering why the functions are not working with types of the same kind ? See the following pseudo functions.
Playground: http://play.golang.org/p/ZG1jU8H2ZJ
package main
type typex struct {
email string
id string
}
type typey struct {
email string
id string
}
func useType(t *typex) {
// do something
}
func main() {
x := &typex{
id: "somethng",
}
useType(x) // works
y := &typey{
id: "something",
}
useType(y) // doesn't work ??
}
As to the why - Y is not X so why would it work?
You can easily overcome this, if they really are identical, by casting typey into typex:
useType((*typex)(y))
However, if they are identical, why have 2 types?
Because they are separate types.
What you're after is an interface that Go can use to guarantee that the types contain the same signatures. Interfaces contain methods that the compiler can check against the types being passed in.
Here is a working sample: http://play.golang.org/p/IsMHkiedml
Go won't magically infer the type based on how you call it. It will only do this when it can guarantee that the argument at the call site matches that of the input interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With