Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does new applied to an interface mean?

Tags:

go

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 ?

like image 777
canadadry Avatar asked Feb 26 '14 19:02

canadadry


People also ask

What does it mean program to 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.

What is an example of an interface?

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".

What is the purpose of an interface?

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.

How do I create a new interface?

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.


1 Answers

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

like image 76
Volker Avatar answered Sep 24 '22 23:09

Volker