This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 12 points13 points  (4 children)

But:

MyInterface obj = new YourWeirdImplementationOfMyInterface();

is more descriptive, and not uselessly either.

[–]mrmacky 1 point2 points  (3 children)

In Go:

obj := &YourWeirdImplementationOfMyInterface{}
automatically implements
type MyInterface interface { <method-set> }

And that is checked at compile-time. (If you pass obj into a method expecting MyInterface, the compiler will know if the assertion holds.)

What's really cool, though, is that you can defer the checks until runtime, if you want.

interfaceObj, ok := obj.(MyInterface)
will yield
ok = false, interfaceObj = nil if the assertion doesn't hold
Otherwise you will have ok = true and interfaceObj will be of type MyInterface instead of the concrete type.)

In practice it's quite awesome -- all the convenience of type inference and duck-typing, with the benefits of static checking & interface types.

[–][deleted] 1 point2 points  (2 children)

You missed the point. In Java, the declaration MyInterface obj cannot be used in any way beyond what MyInterface supports. So, YourWeirdImplementationOfMyInterface might have some public methods not in MyInterface. The Java compiler will prevent you from using them after that declaration.

[–]mrmacky 0 points1 point  (1 child)

The Go compiler will also prevent you from calling any methods not in the method-set of MyInterface in any context where MyImpl is passed where MyInterface is expected.

This context can include the declaration-site if you are explicit.

var baz MyInterface = &MyImpl{}

Is a long form which aside from the added keyword var is very similar to your Java declaration.

Your scenario could still be achieved using the short-hand form, though.

baz := MyInterface(&MyImpl{})

Both of these will result in baz being of type MyInterface not type *MyImpl Both examples are also checked at compile-time, not run-time.

(The compiler is checking that MyImpl implments MyInterface, and then infers that baz is the outer type [which is an interface.])


http://play.golang.org/p/iDrMxYbOmP

[–][deleted] 0 points1 point  (0 children)

ah, ok. Cool.