On Sunday, 12 April 2020 18:12:16 UTC+1, Tanmay Das wrote: > > this is not my first statically typed language, I know a little bit of C > and Java. I was under the impression that Go is capable of some dynamic > behavior. Maybe things like Go's type inference, duck typing, empty > interface{} led me to believe that. All these type-related bindings can be > resolved at compile-time. So I was thinking, if the compiler can do some > extra work for resolving the types, maybe it could add a few more steps to > keep track of which function to call when an undefined method is accessed.
There's no type inference in go, except for defining a variable and initializing it from an expression at the same time: v := foo() In this case you don't need to declare the type of v, because it's implied from the return type of foo. The nearest to dynamic typing (and indeed duck typing) is interfaces. You can define an interface such as: type Foo interface { Bar() } and then declare a variable of that type: var v Foo When you later assign something to var v, you can only assign a value of some type which includes the Bar() method. This is statically enforced (at compile time): you simply can't write a program which assigns a value which doesn't have the Bar() method. https://play.golang.org/p/hYZNPx0L187 Note that the types you create which include a Bar() method *don't* need to declare that they implement the Foo interface; this is implicit by the fact that they have the correct methods, which makes it rather like duck-typing. Interfaces with only a single method are very common, since the same object can implement many different interfaces if required. This feature gives a huge amount of flexibility. For example, the io.Reader <https://tour.golang.org/methods/21> interface is simple but pervasive. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/806dea52-5f12-4647-acd6-577960f0059d%40googlegroups.com.