I understand that if T
is a struct, then this amounts to creating an empty struct (sensible empty values)::
t := new(T)
However, given the following snippet::
type Burper interface {burp() int}
b := new(Burper)
What is created & what is the usefulness of new'ing an interface ?
"Programming to an interface" means, that when possible, one should refer to a more abstract level of a class (an interface, abstract class, or sometimes a superclass of some sort), instead of refering to a concrete implementation.
An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".
Interfaces are useful for the following: Capturing similarities among unrelated classes without artificially forcing a class relationship. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class.
To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default.
This just creates a pointer to a Burper (which is an interface). As there is (almost) no sensible use for a pointer to an interface this is valid Go, harmless and useless in practice.
b
is a pointer and points to the zero value of Burper which is nil.
See http://play.golang.org/p/r6h8KiA9pa
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