Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why you can't use a type from a different package if it has the same 'signature' ? golang

Tags:

go

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 ??
}
like image 444
user3721073 Avatar asked Jun 24 '14 10:06

user3721073


2 Answers

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?

like image 99
Not_a_Golfer Avatar answered Sep 28 '22 07:09

Not_a_Golfer


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.

like image 27
Simon Whitehead Avatar answered Sep 28 '22 07:09

Simon Whitehead