Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang interface compliance compile type check

I see the following statements from camlistore(http://code.google.com/p/camlistore/source/browse/pkg/cacher/cacher.go).

var (
        _ blobref.StreamingFetcher = (*CachingFetcher)(nil)
        _ blobref.SeekFetcher      = (*CachingFetcher)(nil)
        _ blobref.StreamingFetcher = (*DiskCache)(nil)
        _ blobref.SeekFetcher      = (*DiskCache)(nil)
)

I understand that no variables are created and the statements ensure compiler checks that CachingFether implements public functions of StreamingFetcher and SeekFetcher. RHS portion uses a pointer constructor syntax with a nil parameter. What does this syntax mean in Go language ?

like image 578
satish Avatar asked Aug 01 '13 12:08

satish


People also ask

How can I guarantee my type satisfies an interface?

How can I guarantee my type satisfies an interface? You can ask the compiler to check that the type T implements the interface I by attempting an assignment using the zero value for T or pointer to T , as appropriate: type T struct{} var _ I = T{} // Verify that T implements I.

What is interface {} Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.

Can a struct have an interface Golang?

The interface is a contract of implicit behaviors (object methods) you invoke as needed without the rigors of explicit declaration. These methods are then added onto user-defined structs to create an interface that is about behavior, not data.

How do you implement an interface in Golang?

Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.


1 Answers

(*T)(nil) is a Conversion. In this case it stands for a typed nil, ie. the same value which, for example

var p *T

has before assigning anything to it.

The standard syntax of a conversion is T(expr), but the priority of the * would bind it wrongly in

*T(expr)

This syntax means dereferencing the return value of function T with one argument expr. That's why the conversion has an alternative syntax:

(T)(expr)

where T can of course be *U. Therefore

(*U)(expr)

is the generalized form of what you see in the Camlistore repository.

like image 53
zzzz Avatar answered Oct 12 '22 01:10

zzzz