I'm really struggling to find a name for a type of function I've come across.
Here is the function in question:
https://github.com/go-fsnotify/fsnotify/blob/master/fsnotify.go#L32
This is how I'm using it (as per the fsnotify example):
select {
case event := <-watcher.Events:
log.Println("Event Triggered: ", event)
In that Println 'event' is returning the formatted string as per the function above, I'm just struggling to understand how a straight call to 'event' is using that function yet I would be expecting it to be accessed like the struct fields (event.Name, event.Op):
event.funcForReturningNicelyFormattedEvent()
It feels like this is a 'default' function as it has no name and it just returns the formatted data - I'm struggling to come up with the name/type/search term so I can find out more and understand the concept and importantly the reasoning behind it better.
Any help is appreciated.
It's very simple - println uses the String() method on any struct that implements it automatically. This is a classic use case of Go's implicit interfaces: every struct that has the methods an interface includes, is considered to be implementing the interface.
If it has func String() string it is considered a Stringer and used by fmt. You can use it on your own structs too, of course.
Function Println checks if the passed value implements interface Stringer. If it does it calls method String on this value. Event type implements that interface by supplying its implementation of String method in the excerpt you linked to.
In Go you don't have to declare that you implement interface.
Related
I have below code try to assign embed struct to its parent struct. There are two set of structure: Guider is the parent struct, DataBlock extends from it. The method func Put(x Guider) accept a parameter with type Guider. It works when I pass a DataBlock variable.
However, the other case is Mock extends from zerolog.Event, but it fails to pass the parameter on the method Test(e zerolog.Event)
I got the following error:
cannot use m (variable of type Mock) as type zerolog.Event in argument to Test
Why are these two cases works differently? How can I make them both work?
package main
import (
"fmt"
"github.com/rs/zerolog"
)
type Guider interface {
Guid() string
}
type FSEntity struct {
guid string
}
func (e FSEntity) Guid() string {
return e.guid
}
func Put(x Guider) {
fmt.Printf("%+v\n", x)
}
type Mock struct {
zerolog.Event
}
func Test(e zerolog.Event) {
}
//Child struct:
type DataBlock struct {
FSEntity
data []byte
}
func main() {
myVar := DataBlock{}
myVar.guid = "test"
myVar.data = []byte("moar test")
Put(myVar) // it works
m := Mock{}
Test(m) // it doesn't work. cannot use m (variable of type Mock) as type zerolog.Event in argument to Test
}
First, a couple of definitions:
Polymorphism
Polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.
Subtyping
Subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, meaning that program elements, typically subroutines or functions, written to operate on elements of the supertype can also operate on elements of the subtype
Inheritance
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object (prototype-based inheritance) or class (class-based inheritance), retaining similar implementation.
Object composition
Object composition and object aggregation are closely related ways to combine objects or data types into more complex ones.
Golang follows composition over inheritance principle, e.g. it doesn't support inheritance. So when you're saying
Mock extends from zerolog.Event
you actually mean that Mock includes zerolog.Event struct.
The way Golang implements polymorphism is interface. All types that implement some interface can be used in its place. It's what you see when use Guider.
However, it doesn't work for simple structs. zerolog.Event is a struct inside Mock.
So, normally, Test function should accept some interface as a parameter, and both mock and real event should implement this interface. However, it looks like zerolog doesn't provide interface for Event. So instead you should access the Event field of you struct. Example
Put(myVar) is legal because myVar is a DataBlock which contains (not inherits from and not implements) an FSEntity which in turn implements the Guider interface.
Since Put accepts a Guider, the reference to myVar is compatible, by virtue of the anonymous FSEntity field it contains which implements Guider. The implementation of Guider on FSEntity is (in effect) elevated to the containing struct (providing a means of delegating interfaces). This only occurs if the contained field is anonymous.
But in the case of Test(m), the function accepts a zerolog.Event which is a struct type, not an interface. As such, there is no "delegation" possible. Test() must be passed a zerolog.Event and in this scenario, this requires that you use the type name of the anonymous field:
Type(m.Event)
Some bonus info:
If DataBlock contained two anonymous fields which both implemented Guider then implicit delegation/elevation cannot take place; golang does not know which of the contained implementations should be delegated to/elevated (if any). In that scenario you must again use the name of the field that you wish to pass to the Put() function:
// given...
type Foo string
func (f Foo) Guid() string {
return string(f)
}
// and...
type DataBlock struct {
FSEntity
Foo
data []byte
}
// then...
Put(myVar) // is now illegal
// and must instead use either/or:
Put(myVar.FSEntity)
Put(myVar.Foo)
Whether implicit or explicit, the crucial distinction is that it is a field of the DataBlock (myVar) that is passed to Put(), not myVar itself.
If you want to pass the DataBlock to Put(), using a Guider interface, then DataBlock must itself implement the Guider interface.
Take this with a grain of salt, since I'm not familiar with zerolog package.
Your Guider is an interface, which might have any underlying type as long as Guid() method is satisfied. I assume this is happening through DataBlock containing FSEntity, which itself implements Guid() method, therefore satisfies MIGHT the interface.
On the other hand, I don't know what methods should be implemented to satisfy zerolog.Event or if it's even an interface, or a struct straight up. If it's an interface, you might need to implement it's required methods to be able to use DataBlock as zerolog.Event type. You might want/need to dig into that direction for some very specific answers.
I am referring to the code in this link: Interfaces in Golang
Under the "Type assertions" section, the first piece of code has a line like so in the main function: var val interface {} = "Geeks for Geeks"
I did not understand this syntax. Usually, we create an interface type at the package level like
type some_interface interface {
// methods
}
and then create a variable of this interface type var s some_interface for use. What does this line actually do? Is it an "anonymous interface" (like anonymous struct). What is the use of declaring an interface using this method?
Thanks in advance
It is an empty interface, basically any type.
The empty interface
The interface type that specifies zero methods is known as the empty
interface:
interface{}
An empty interface may hold values of any type. (Every type implements
at least zero methods.)
Empty interfaces are used by code that handles values of unknown type.
For example, fmt.Print takes any number of arguments of type
interface{}.
I am trying to see if Go supports a language feature I use in other OO languages (such as Java). I'd like to define a few interfaces and pass an object that supports some of them to a function as a parameter.
In Java I might define a bunch of single method interfaces like HasAdd, HadMul, HasSub, HasDiv, HasSin, HasCos, HasTan, etc.
And then I might define a generic method whose argument T is defined as <T extends HasSin & HasAdd>. I pass in a T to the method. Note I don't have to define an intermediate Interface that contains both HasSin and HasAdd. (Which is great because n interfaces results in needing 2^n intermediate interfaces to cover all cases).
I know go does not support generics. But can it do something like func(HasSin & HasAdd obj)? It seems it should support this behavior. I just haven't found documentation that cinches it either way.
I have seen this: https://golangbot.com/interfaces-part-2/ where there is an example of something similar near the bottom of the article but it does indeed use an intermediate interface.
Declare an interface with the methods required by the function:
type SinAdder interface {
Sin(float64) float64
Add(float64, float64) float64
}
If you declared the single method interfaces Siner and Adder, then you can declare SinAdder in terms of those interfaces:
type SinAdder interface {
Siner
Adder
}
Use that interface in the function:
func example(arg SinAdder) {
}
Any value that has the Sin and Add methods can be passed to example.
You can void declaring the SinAdder interface by using an anonymous interface definition in the function argument:
func example(arg interface { Siner; Adder }) {
}
I get cannot use map[string]MyType literal (type map[string]MyType) as type map[string]IterableWithID in argument to MapToList with the code below, how do I pass in a concrete map type to method that expects a interface type?
https://play.golang.org/p/G7VzMwrRRw
Go's interface convention doesn't quite work the same way as in, say, Java (and the designers apparently didn't like the idea of getters and setters very much :-/ ). So you've got two core problems:
A map[string]Foo is not the same as a map[string]Bar, even if Bar implements Foo, so you have to break it out a bit (use make() beforehand, then assign in a single assignment).
Interface methods are called by value with no pointers, so you really need to do foo = foo.Method(bar) in your callers or get really pointer-happy to implement something like this.
What you can do to more-or-less simulate what you want:
type IterableWithID interface {
SetID(id string) IterableWithID // use as foo = foo.SetID(bar)
}
func (t MyType) SetID(id string) IterableWithID {
t.ID = id
return t
}
...and to deal with the typing problem
t := make(map[string]IterableWithID)
t["foo"] = MyType{}
MapToList(t) // This is a map[string]IterableWithID, so compiler's happy.
...and finally...
value = value.SetID(key) // We set back the copy of the value we mutated
The final value= deals with the fact that the method gets a fresh copy of the value object, so the original would be untouched by your method (the change would simply vanish).
Updated code on the Go Playground
...but it's not particularly idiomatic Go--they really want you to just reference struct members rather than use Java-style mutators in interfaces (though TBH I'm not so keen on that little detail--mutators are supes handy to do validation).
You can't do what you want to do because the two map types are different. It doesn't matter that the element type of one is a type that implements the interface which is the element type of the other. The map type that you pass into the function has to be map[string]IterableWithID. You could create a map of that type, assign values of type MyType to the map, and pass that to the function.
See https://play.golang.org/p/NfsTlunHkW
Also, you probably don't want to be returning a pointer to a slice in MapToList. Just return the slice itself. A slice contains a reference to the underlying array.
The Go Tour says the following:
You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package (which includes the built-in types such as int).
Is there a reason for this other than avoiding everyone building their own methods off int and string? I've Googled around, but can't find anything referencing it.
The reason is that if you could define methods on other packages' types, you could modify the behavior of other packages. This is because the method set of a given type can have an effect on how values of that type are used.
Consider, for example, the fmt.Println function. When you pass an argument to fmt.Println, it will print a string representation of that value based on a set of rules. One of those rules is that if the type of the value has a String() string method (that is, it implements the fmt.Stringer interface), then that method will be called in order to obtain the string representation of the value.
Thus, imagine that we have a package, foo, and that package has a type, FooInt, defined as follows:
type FooInt int
Now imagine that this package also has a function, PrintFooInt:
func PrintFooInt(f FooInt) { fmt.Println(f) }
This will print the integer value of f. But let's say that you (in a different package, say main) were able to add methods to FooInt. Then you could do this:
func (f FooInt) String() string { return "foobar!" }
This would actually change the behavior of foo.PrintFooInt, which shouldn't be possible from outside the package.